I work for a government client and our deployments are controlled by another contractor who has requested we provide powershell scripts to run our database scripts. Unfortunately security is tight and I don't have permissions to add powershell snapins so I have to use good old sqlcmd instead of Invoke-Sqlcmd. I am having trouble getting errors generated from running the scripts to be passed back to powershell.
For example imagine in the scenario below that "02 test2.sql" has an error that causes it to fail to run. I would like this to terminate the script, log a message to the console and also log the output of sqlcmd to a file. No matter what I try I can't seem to get a sqlcmd failure to be recognized by PowerShell.
function TerminateScript {
ECHO "Please email `"Production.log.txt`" to [email protected]"
Read-Host -Prompt "Press Enter to exit"
exit 1
}
ECHO "Running `"01 test1.sql`"" | tee -a Production.log.txt
sqlcmd -r -b /S serverName /d dbName -i "01 test1.sql" >> Production.log.txt
if ($LASTEXITCODE -ne 0) {
Write-Error "Error occured while running `"01 test1.sql`". Terminating script."
TerminateScript
}
ECHO "Running `"02 test2.sql`"" | tee -a Production.log.txt
sqlcmd -r -b /S serverName /d dbName -i "02 test2.sql" >> Production.log.txt
if ($LASTEXITCODE -ne 0) {
Write-Error "Error occured while running `"02 test2.sql`". Terminating script."
TerminateScript
}
ECHO "Running `"03 test3.sql`"" | tee -a Production.log.txt
sqlcmd -r -b /S serverName /d dbName -i "03 test3.sql" >> Production.log.txt
if ($LASTEXITCODE -ne 0) {
Write-Error "Error occured while running `"03 test3.sql`". Terminating script."
TerminateScript
}