Does Powershell forget to set ERRORLEVEL on parser errors?
Asked Answered
I

1

8

In a command prompt, Try this out:

powershell aaa

echo ErrorLevel is %errorlevel%

Powershell will fail (with an error). You will also see "ErrorLevel is 1". This is because it runs aaa as a script, which makes an unhandled error, which sets the errorlevel.

However, now try this:

powershell '

echo ErrorLevel is %errorlevel%

Powershell will fail (with an error). This time, you will also see "ErrorLevel is 0".

I realize it's a different problem. Powershell even will say it's a ParserError, and it's because I screwed up the command line arguments. Still, that's not cool.

I am unclear as to why it behaves this way. I'm guessing this was an oversight. Other programs out there neglect setting errorlevel on failures, but in this case it's as if they went halfway. It's even setting it to 0 here as opposed to not setting it at all.

Intrust answered 15/12, 2011 at 19:40 Comment(4)
One minor correction: there isn't any way for a console application to not set the error level. This is only possible for internal commands.Budd
Windows Script Host (cscript) has a similar problem. Presumably MS see Powershell and WSH as alternatives to rather than clients of the command shell.Budd
One workaround is for your Powershell/WSH script to return a specific non-zero value on success; -1 might be a good choice.Budd
I would agree that the "-1" idea Harry Johnston mentions would be a good alternative if the need is great enough and the situation allows for it.Intrust
C
1

Hmm I think I agree that a parse error should set the return code to non zero. I suggest filing this over at the the Powershell connect site. http://connect.microsoft.com/PowerShell

Cleliaclellan answered 16/12, 2011 at 10:21 Comment(1)
I figure we've picked the community brain as much as possible on this one. I wouldn't mind having to deal with the "0" return code if there was a good reason, but I figure that the behavior for this situation was just not deliberately defined.Intrust

© 2022 - 2024 — McMap. All rights reserved.