Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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


110 changes: 91 additions & 19 deletions sql.ps1
Original file line number Diff line number Diff line change
@@ -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}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Formatting the table view


$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
#>