As Guenther Schmitz already explained, $host.SetShouldExit($exitcode)
and exit
are 2 distinct statements that must be separated either with a newline or a semicolon.
Without that separation your code should have thrown a different error, though:
Unexpected token 'exit' in expression or statement.
The error you posted looks more like you tried to use that function without defining it first.
The purpose of the function is to set a proper exit code when exiting from a script regardless of how the script was run. Normally you'd run PowerShell scripts like this:
powershell.exe -File "C:\your.ps1"
And in that case a simple exit $exitcode
would be sufficient:
C:\> type test1.ps1
exit 23
C:\> powershell -File .\test1.ps1
C:\> echo %errorlevel%
23
However, another way to execute PowerShell scripts is the -Command
parameter (since PowerShell scripts can be run directly from PowerShell). The difference between the -File
and -Command
parameters is that the latter returns only 1 or 0 (indicating whether or not the script exited with a non-zero exit code), but not the exit code itself.
C:\> powershell -Command .\test1.ps1
C:\> echo %errorlevel%
1
When omitting the parameter entirely PowerShell defaults to -Command
(allowing you to easily run PowerShell statements from the commandline):
C:\> powershell .\test1.ps1
C:\> echo %errorlevel%
1
Defining an exit code via $host.SetShouldExit()
ensures that the exit code is returned correctly when the script is invoked via powershell. -Command
. You still should exit with the actual exit code, though, because otherwise the exit code would only be set when running the script via powershell.exe -Command
, but not when running the script via powershell.exe -File
:
C:\> type test2.ps1
function ExitWithCode($exitcode) {
$host.SetShouldExit($exitcode)
exit
}
ExitWithCode 23
C:\> powershell -File .\test2.ps1
C:\> echo %errorlevel%
0 # ← exit without argument defaults to 0!
C:\> powershell -Command .\test2.ps1
C:\> echo %errorlevel%
23
C:\> type test3.ps1
function ExitWithCode($exitcode) {
$host.SetShouldExit($exitcode)
exit $exitcode
}
ExitWithCode 23
C:\> powershell -File .\test3.ps1
C:\> echo %errorlevel%
23
C:\> powershell -Command .\test3.ps1
C:\> echo %errorlevel%
23