Skip to content

Instantly share code, notes, and snippets.

@niaher
Created April 4, 2014 11:24
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 niaher/9972627 to your computer and use it in GitHub Desktop.
Save niaher/9972627 to your computer and use it in GitHub Desktop.
function Read-Query
{
param (
[Parameter(Mandatory=$true)]
[string]$ConnectionString,
[Parameter(Mandatory=$true)]
[string]$Query,
[Parameter(Mandatory=$true)]
[scriptblock]$Action
)
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $ConnectionString
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $Query
$SqlCmd.Connection = $SqlConnection
$reader = $SqlCmd.ExecuteReader()
while ($reader.Read())
{
$x = $null
$x = @{}
for ($i = 0; $i -lt $reader.FieldCount; ++$i)
{
$x.add($reader.GetName($i), $reader[$i])
}
& $action $x
}
$SqlConnection.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment