Found plenty of examples online how to do the following in powershell:
Get-ChildItem $databaseFolder -Filter *.sql -Recurse | ForEach-Object { sqlcmd -S $databaseServer -d $databaseName -E -i $_.FullName }
However, I'd like to group this under one single transaction so if one of the sql files fails, then everything is rolled back.
One alternative that I am also trying is to put together all the file contents in to a full script variable:
foreach( $file in Get-ChildItem -path $databaseFolder -Filter *.sql | sort-object )
{
Get-Content $file.fullName | Foreach-Object { $fullSqlScript = $fullSqlScript + $_ + "`n" } ;
}
And then execute that in the end like so:
invoke-sqlcmd -ServerInstance $databaseServer -Database $databaseName -Query $fullSqlScript | format-table | out-file -filePath $outFile
The $fullSqlScript would also have the following inserted at the top:
:On Error Exit
SET XACT_ABORT ON
GO
Begin Transaction
and end:
IF XACT_STATE() = 1
BEGIN
PRINT 'Committing Transaction...'
COMMIT TRANSACTION
END
ELSE IF XACT_STATE() = -1
BEGIN
PRINT 'Scripts Failed... Rolling back'
ROLLBACK TRAN
END
However, as soon as I make an intentional sql script fail then the entire database is locked up like the transaction cannot be rolled back. I'm assuming this has something to do with invoke-sqlcmd being used in a powershell script environment rather than sqlcmd from windows command prompt?