Handy SQL Function in PowerShell
In a previous post I described a little about PowerShell and SQL, how to connect and how to handle different queries through PowerShell.
Now let’s put it all togheter and create a more handy function.
function Get-SQL ([string]$Query,[string]$ConnString) {
if ($ConnString) {
if($ConnString -match '"*"') {
$ConnString = $ConnString.TrimStart('"')
$ConnString = $ConnString.TrimEnd('"')
}
} else {
# Default Connection String
$ConnString =
"server=ServerName;database=DbName;trusted_connection=true;"
}
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = $ConnString
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $Query
$Reader = $Command.ExecuteReader()
$Counter = $Reader.FieldCount
while ($Reader.Read()) {
$SQLObject = @{}
for ($i = 0; $i -lt $Counter; $i++) {
$SQLObject.Add(
$Reader.GetName($i),
$Reader.GetValue($i));
}
$SQLObject
}
$Connection.Close()
}
Examples on Running the Function:
PS > Get-SQL "SELECT * FROM Products" PS > Get-SQL "SELECT * FROM Products" ` -Server "server=NewServer;database=DbName;trusted_connection=true;"
[?]
