Problem is that this will always return as 0 aka success even if something goes wrong in the script (syntax error etc.) How can I get the real exit code when running PowerShell scripts this way?
C:\>powershell.exe -ExecutionPolicy Bypass -NoProfile -Command "& c:\windows\asdf.exe"
& : The term 'c:\windows\asdf.exe' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:3
+ & c:\windows\asdf.exe
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (c:\windows\asdf.exe:String) [],
CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
C:\>echo %errorlevel%
1
PowerShell doesn’t really write to stderr in the way you’re thinking; you’d need to have the script use Write-Output to produce some result, which will be returned to stdout. Or, as noted, use the Exit command to set something to stderr.