functions/private/Invoke-SqlCommand.ps1
function Invoke-SqlCommand { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $sqlServerAddress, [String] $databaseName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $query, [PSCustomObject] $parameters = @{}, [Boolean] $returnData = $false ) $connectionString = "Data Source=$sqlServerAddress;Initial Catalog=$databaseName; Trusted_Connection=True;" $connection = New-Object System.Data.SqlClient.SQLConnection($connectionString) $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection) try { foreach ($p in $parameters.Keys) { $command.Parameters.AddWithValue("@$p", $parameters[$p]) | Out-Null } $connection.Open() if ($returnData) { $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command $dataset = New-Object System.Data.DataSet $adapter.Fill($dataSet) | Out-Null $dataSet.Tables } else { $command.ExecuteNonQuery() | Out-Null } $connection.Close() } catch [System.Data.SqlClient.SqlException] { Write-DosMessage -Level "Error" -Message "An error ocurred while executing the command. Connection String: $($connectionString) Query: $query" -ErrorAction Continue throw $_.Exception } } |