I’ve got a simple powershell script like this:
Set-Strictmode -version Latest
$ErrorActionPreference = 'Stop'
try
{
Write-Host "aaa $(MyFunc "bbb)"
}
catch
{
Write-Host "Caught the error!"
Write-Host $error
exit 666
}
(Note that this script has an error in the first Write-Host line.)
I need my scripts to run in such a way that if there are any errors, it will return with a non-zero value. This is the purpose of setting “Set-Strictmode”, “$ErrorActionPreference”, and wrapping it all in a try…catch block.
But when I run it from the windows cmd.exe, you can see that the error is not caught and that it does not return an error code:
D:\jjj>powershell -F jjj.ps1
At D:\jjj\jjj.ps1:6 char:28
+ Write-Host "aaa $(MyFunc "bbb)"
+ ~~~~~
The string is missing the terminator: ".
At D:\jjj\jjj.ps1:6 char:34
+ Write-Host "aaa $(MyFunc "bbb)"
+ ~
Missing closing ')' in subexpression.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
D:\jjj>echo Exit Code is %errorlevel%
Exit Code is 0
I suspect that the unmatched quotes in the errorful line is mangling the interpretation so much that the try…catch block is never properly instantiated.
So, here’s the question: what can I do to ensure that any execution errors of my PowerShell script cause it to return with a non-zero errorcode?