Last active
November 4, 2015 11:46
-
-
Save matt40k/a05f6b1e6763d7e5182b to your computer and use it in GitHub Desktop.
Example of a SQL select query using PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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