Skip to content

Instantly share code, notes, and snippets.

@matt40k
Last active November 4, 2015 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt40k/a05f6b1e6763d7e5182b to your computer and use it in GitHub Desktop.
Save matt40k/a05f6b1e6763d7e5182b to your computer and use it in GitHub Desktop.
Example of a SQL select query using PowerShell
$ServerName = '.'
$DatabaseName = 'Demo'
function Execute-SqlQuery($query) {
$a = @()
try {
$connectionString = 'Server='+$ServerName+';Database='+$DatabaseName+';Integrated Security=True;'
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$Datatable = New-Object System.Data.DataTable
$connection.Open()
$sqlCommand = $connection.CreateCommand()
$sqlCommand.CommandText = $query
$sqlReader = $sqlCommand.ExecuteReader()
$DataTable.Load($sqlReader)
foreach ($rows in $DataTable.Rows)
{
$a += $rows['a']
}
}
catch
{
throw "Error querying database"
}
finally {
$connection.Dispose()
}
return $a
}
$SqlQuery = 'SELECT 1 as A;'
$sqlResults = Execute-SqlQuery($SqlQuery)
foreach ($item in $sqlResults)
{
Write-Host $item
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment