Created
March 30, 2016 00:13
-
-
Save RandomNoun7/a943d8dac1788ca91da775d5d89a3393 to your computer and use it in GitHub Desktop.
Custom Invoke SQL Query Script after I got annoyed with SQLPS from SQL 2008r2
This file contains hidden or 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
function Invoke-BHSQLProc | |
{ | |
param | |
( | |
[cmdletBinding()] | |
[string]$server = $env:COMPUTERNAME, | |
[parameter(Mandatory = $true)] | |
[string]$dbname, | |
[parameter(Mandatory = $true)] | |
[string]$proc, | |
[hashtable[]] | |
$params | |
) | |
<# | |
.SYNOPSIS | |
Execute a stored procedure in a database using current users credentials | |
.DESCRIPTION | |
Specify a server name, a database name, a procedure name, and parameters. The function will execute the | |
procedure and return the results as a set of data tables. | |
#> | |
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection | |
$SqlConnection.ConnectionString = "Server=$server;Database=$dbname;Integrated Security=True" | |
Write-Verbose "Invoke-HnSqlProc: Connection string: ""Server=$server;Database=$dbname;Integrated Security=True""" | |
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand | |
$SqlCmd.CommandType = 'StoredProcedure' | |
$SqlCmd.CommandText = $proc | |
$SqlCmd.CommandTimeout = 0 | |
if ($params) | |
{ | |
foreach ($param in $params.GetEnumerator()) | |
{ | |
Write-Verbose "Invoke-HnSqlProc: Params: Name: $($param.name) Value: $($param.value) Type: $($param.type) Length: $($param.length)" | |
if ($param.type -eq 'VarChar') | |
{ | |
$SqlCmd.Parameters.Add($param.name, $param.type, $param.length) | Out-Null | |
} | |
else | |
{ | |
$SqlCmd.Parameters.Add($param.name, $param.type) | Out-Null | |
} | |
$SqlCmd.Parameters[$param.name].Value = $param.value | |
} | |
} | |
$SqlCmd.Connection = $SqlConnection | |
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter | |
$SqlAdapter.SelectCommand = $SqlCmd | |
$DataSet = New-Object System.Data.DataSet | |
$SqlAdapter.Fill($DataSet) | Out-Null | |
$SqlCmd.Dispose() | |
$SqlConnection.Dispose() | |
$SqlAdapter.Dispose() | |
Write-OutPut ($dataset.tables.GetEnumerator() | Select -expandProperty rows) | |
$DataSet.Dispose() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment