Skip to content

Instantly share code, notes, and snippets.

@Warrenn
Created August 18, 2022 16:27
Show Gist options
  • Save Warrenn/10c779deaa386a999c29a6809b6c2569 to your computer and use it in GitHub Desktop.
Save Warrenn/10c779deaa386a999c29a6809b6c2569 to your computer and use it in GitHub Desktop.
execute database update insert or delete
function Execute-NonQuery([psobject[]]$sqlCommands, $connectionString) {
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$connection.Open()
$command = $connection.CreateCommand()
$transaction = $connection.BeginTransaction()
$command.Connection = $connection
$command.Transaction = $transaction
try {
for($i=0;$i -lt $sqlCommands.Length;$i++){
$command.CommandText = $sqlCommands[$i].commandText
$parameters = $sqlCommands[$i].parameters
$command.Parameters.Clear()
$parameters | Select-Object -ExpandProperty Keys | %{
$command.Parameters.Add($_, $parameters[$_])
}
$command.ExecuteNonQuery()
}
$transaction.Commit()
}
catch {
$transaction.Rollback()
}
finally {
$connection.Close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment