I recently published a new module for interacting with databases that supports transactions:
Install-Module -Name InvokeQuery
You don't need to explicitly roll back if an error occurs. The ambient transaction that's created with Start-Transaction
will take care of that for you.
try {
$db = "test"
Start-Transaction
$sql = "insert into table1 values (NEWID(), 8765, 'transactions!', GETDATE())"
$rowcount = $sql | Invoke-SqlServerQuery -Database $db -UseTransaction -CUD -Verbose
Write-Host "Inserted $rowcount rows!"
$sql = "insert into table1 values (NEWID(), 5555, 'transaction too!', GETDATE())"
$rowcount = $sql | Invoke-SqlServerQuery -Database $db -UseTransaction -CUD -Verbose
Write-Host "Inserted $rowcount rows!"
Complete-Transaction
}
catch {
##Transaction will automatically be rolled back....
Write-Error $_
}
If you want to explicitly roll back within the transaction then throw an error:
throw 'rollback because of reason X!'
More examples:
https://github.com/ctigeek/InvokeQueryPowershellModule/blob/master/README.md#transactions