From ea936a43ad4987f2098c24b75c4bea346c94b226 Mon Sep 17 00:00:00 2001 From: owen Date: Thu, 4 Feb 2016 09:50:37 +0000 Subject: [PATCH 1/2] Reformatted in to separate functions for easier reuse. Will need to load the functions first and then call them as required. --- sql.ps1 | 110 ++++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 91 insertions(+), 19 deletions(-) diff --git a/sql.ps1 b/sql.ps1 index 5b60448..bf846ac 100644 --- a/sql.ps1 +++ b/sql.ps1 @@ -1,28 +1,100 @@ -$dataSource = ".\SQLEXPRESS" -$user = "user" -$pwd = "1234" -$database = "Test" -$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;" +Function Connect-SQLServer +{ +[cmdletbinding()] +Param( + $dataSource = ".\SQLEXPRESS", + $database = "Test", + [Parameter(ParameterSetName="UserAutentication")]$user = "user", + [Parameter(ParameterSetName="UserAutentication")]$pwd = "1234", + [Parameter(ParameterSetName="IntegratedSecurtity")][switch]$IntegratedSecurtity + ) -$query = "SELECT * FROM Person" + If($IntegratedSecurtity) + { + $connectionString = "Server=$dataSource;Database=$database;Integrated Security=True;" + } + Else + { + $connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;" + } + $connection = New-Object System.Data.SqlClient.SqlConnection + $connection.ConnectionString = $connectionString + $connection.Open() + Write-Output $connection +} +<# +.EXAMPLE $SqlSession = Connect-SQLServer + Uses all the default values to replicate the original script. -$connection = New-Object System.Data.SqlClient.SqlConnection -$connection.ConnectionString = $connectionString -#$connection.ConnectionString = "Server=$dataSource;Database=$database;Integrated Security=True;" -$connection.Open() -$command = $connection.CreateCommand() -$command.CommandText = $query + Stores the SQL session in the $SqlSession variable for use later. -$result = $command.ExecuteReader() +.EXAMPLE $SqlSession = Connect-SQLServer -dataSource "localhost" -database "SlickTicket" -IntegratedSecurtity + Connects to the SlickTicket DB on Localhost using Integrated Security -$table = new-object “System.Data.DataTable” -$table.Load($result) + Stores the SQL session in the $SqlSession variable for use later. +#> -$format = @{Expression={$_.Id};Label="User Id";width=10},@{Expression={$_.Name};Label="Identified Swede"; width=30} -$table | Where-Object {$_.Surname -like "*sson" -and $_.Born -lt 1990} | format-table $format +function Get-SQLTableQuery +{ +[cmdletbinding()] +Param( + $SQLSession, + $Query = "SELECT * FROM Person" + ) -$table | Where-Object {$_.Surname -like "*sson" -and $_.Born -lt 1990} | format-table $format | Out-File C:\Users\Iris\Documents\swedes.txt + $command = $SQLSession.CreateCommand() + $command.CommandText = $Query -$connection.Close() + $result = $command.ExecuteReader() + + $table = new-object “System.Data.DataTable” + $table.Load($result) + + Write-Output $table + +} +<# + +.EXAMPLE + + $results = Get-SQLTableQuery -SQLSession $SqlSession + $format = @{Expression={$_.Id};Label="User Id";width=10},@{Expression={$_.Name};Label="Identified Swede"; width=30} + $results | Where-Object {$_.Surname -like "*sson" -and $_.Born -lt 1990} | format-table $format + $results | Where-Object {$_.Surname -like "*sson" -and $_.Born -lt 1990} | format-table $format | Out-File C:\Users\Iris\Documents\swedes.txt + + Uses all the default values to replicate the original script. + + 1) Collects the output of the SQL query in to the $results variable + 2) Sets the formatting parameters for the host stream + 3) Returns the formatted table (a collection of string, not an object) to the host stream + 4) Pipes the fortmatted table (a collection of string, not an object) to C:\Users\Iris\Documents\swedes.txt + + +.EXAMPLE + + $results = Get-SQLTableQuery -SQLSession $SqlSession -Query "Select * from faq" + $results | Export-CSV -Path "Exported-FAQ-Table.csv" -NoTypeInformation + + + 1) Collects the output of the "Select * from faq" SQL query in to the $results variable + 2) Exports the SQL Table object as a CSV to the "Exported-FAQ-Table.csv" file in the current working directory + +#> + + +Function Disconnect-SQLServer +{ +[cmdletbinding()] +Param( + $SQLSession + ) + + $SQLSession.Close() +} +<# +.EXAMPLE Disconnect-SQLServer -SQLSession $SqlSession + + Cleanly closes the SQL connection +#> \ No newline at end of file From f3e0027d492041cd32899ac555eafd6166eb8d1b Mon Sep 17 00:00:00 2001 From: Owen B Date: Thu, 4 Feb 2016 10:00:59 +0000 Subject: [PATCH 2/2] Created ReadMe file explaining how to use sql.ps1 --- README.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..55e6d3e --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# PowerShell_General + +The sql.ps1 file has been reformatted in to separate functions to make reusing the code easier for different queries. + +The functions will need to be loaded before they can be used. This can be achieved in 2 different ways: + +2. Adding these functions in to a module. + + Modules have a different file extension (psm1) and need to be located in a specific folder structure under the $env:PsModulePath environment variable. + + However once there they are automatically loaded when required in PowerShell V3+ and can be loaded and unloaded manually (using the Import-Module and Remove-Module cmdlets respectively). + + [More information on modules can be found here.](https://technet.microsoft.com/en-us/library/dd878324(v=vs.85).aspx) + + **Modules are the recommended approach for making easily resusable functions in PowerShell.** + +1. Dot-sourcing the sql.ps1 file. + + Assuming the sql.ps1 file is in the current working directory, this is done by running ". .\sql.ps1" (without quotes). + + It's important to note the space between the first dot (.) and the path to sql.ps1 + +