Created
May 26, 2013 19:40
-
-
Save jmosbech/5653796 to your computer and use it in GitHub Desktop.
Executes a Stored Procedure from Powershell and returns the first output DataTable
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
# 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