Skip to content

Instantly share code, notes, and snippets.

@jmosbech
Created May 26, 2013 19:40
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jmosbech/5653796 to your computer and use it in GitHub Desktop.
Save jmosbech/5653796 to your computer and use it in GitHub Desktop.
Executes a Stored Procedure from Powershell and returns the first output DataTable
# Executes a Stored Procedure from Powershell and returns the first output DataTable
function Exec-Sproc{
param($Conn, $Sproc, $Parameters=@{})
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandType = [System.Data.CommandType]::StoredProcedure
$SqlCmd.Connection = $Conn
$SqlCmd.CommandText = $Sproc
foreach($p in $Parameters.Keys){
[Void] $SqlCmd.Parameters.AddWithValue("@$p",$Parameters[$p])
}
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($SqlCmd)
$DataSet = New-Object System.Data.DataSet
[Void] $SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
return $DataSet.Tables[0]
}
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=.\SQLEXPRESS;Database=master;Integrated Security=True"
$Res = Exec-Sproc -Conn $SqlConnection -Sproc "sp_help" -Parameters @{objname="spt_values"}
foreach ($Row in $Res)
{
write-host "output: $($Row[0])"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment