Skip to content

Instantly share code, notes, and snippets.

@TomasBouda
Created March 16, 2020 15:54
Show Gist options
  • Save TomasBouda/06c2c32f7c487fd5e8ecb96b52bcaa52 to your computer and use it in GitHub Desktop.
Save TomasBouda/06c2c32f7c487fd5e8ecb96b52bcaa52 to your computer and use it in GitHub Desktop.
function Invoke-SQL {
param(
[Parameter(Mandatory = $true)]
[string]$DataSource,
[Parameter(Mandatory = $true)]
[string]$Database,
[Parameter(Mandatory = $true)]
[string]$SqlCommand,
[Parameter(Mandatory = $false)]
[switch]$Scalar
)
begin {
$connectionString = "Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog=$Database"
$connection = New-object System.Data.SqlClient.SQLConnection($connectionString)
$command = New-object System.Data.SqlClient.SqlCommand($SqlCommand, $connection)
$connection.Open()
}
process {
if ($Scalar) {
$command.ExecuteScalar()
}
else {
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$dataSet
}
}
end {
$connection.Close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment