Running PowerShell.exe and getting return codes

I need to run some powershell scripts directly from commandline like this:

powershell.exe -ExecutionPolicy Bypass -NoProfile -Command “& {C:\Scripts\MyPowerShellScript.ps1; exit $LastExitCode}”

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?

The way I do something like that is, in the powershell script, exit with a code:

if ( $? -eq $false ) { exit 1 }

then I’d have to run the script with the -file option to get the error code back:

powershell -file whatever.ps1

What you are doing appears to work just fine.

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
C:\>powershell.exe -ExecutionPolicy Bypass -NoProfile -Command "& c:\windows\system32\cmd.exe /c"

C:\>echo %errorlevel%
0
C:\>powershell.exe -ExecutionPolicy Bypass -NoProfile -Command "& c:\windows\system32\cmd.exe /c; exit 12"

C:\>echo %errorlevel%
12

I was thinking of a case like this. test.ps1 contains this, which prints an error message if there’s no file called foo:

dir foo

if I run “powershell -file test.ps1”, it will normally return an errorcode of 0.

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.

Thank you all for the answers.

I eventually figured it out.

Example

Try {

do something

}

Catch {

Exit 1

}

This way I’m able to get it working and return exit code 1 in case of an error.