I am calling sqlcmd from PowerShell to execute a T-SQL script. Currently I am using “:On Error exit” to exit the script if there is an error caused by the data used violating a constraint etc. This is handled by PowerShell detecting the $SqlcmdProcess.ExitCode of 1.
However, if there is a connectivity issue with the database, sqlcmd also gives an ExitCode of 1. Is there a way to set the :On Error ExitCode to something other than 1? I’m aware of using something like :Exit(SELECT 2) to do this, but I’d rather still use :On Error so I don’t have to rewrite the script.
You could use the exit keyword in Powershell. Here’s an example
Create a script called sqlcmdexit.ps1, with something like the following:
Call script and observe exist code:
I’m not aware of any way to set default ExitCode. Using start-process you could something similar: