Powershell always exiting with exit code 1

I'm having an issue on multiple machines for one customer: when running any PowerShell script, the process always exists with exitcode 1, unless an exitcode is explicitly specified in the script (e.g. exit 0).

  • As far as I know, the process should exit with exitcode 0 when the script ran successfully, and when I run this on my own machine, or any server outside of this customer, the exitcode is 0:
    > ver Microsoft Windows [Version 6.3.9600]
    > type test.ps1 Write-Host testing
    > echo %ERRORLEVEL% 0
    > powershell -NoProfile -NonInteractive -NoLogo ./test.ps1 testing
    > echo %ERRORLEVEL% 1

Does anyone know how I can fix this issue?

1

2 Answers

(Continuing from my comment)

These are two completely separate things:

  • > type test.ps1 Write-Host testing
    > echo %ERRORLEVEL% 0
    This is just using Get-Content (if you were in the PowerShell console, not cmd.exe) to display the text in the script:
    • thus command being run here is Get-Content, not your script code
    • unless you are doing this at a cmd prompt, then it's DOS type internal command, not Powershell at all
  • > powershell -NoProfile -NonInteractive -NoLogo ./test.ps1 testing
    > echo %ERRORLEVEL% 1
    • This is actually running the script, by calling powershell.exe from cmd.exe, and is not an apples-to-apples comparison, leading you to false results.
    • Executing echo %ERRORLEVEL% in a PS shell is meaningless, as PS has no idea what %ERRORLEVEL% is in that use context; to see the last error, you use the PS system error variables, not CMD.exe/DOS stuff.

The code you posted is you doing all things in cmd.exe, not PowerShell; ver is DOS internal command, not a PowerShell command:

  • ver /? Displays the Windows version.
    Get-CimInstance -ClassName CIM_OperatingSystem SystemDirectory Organization BuildNumber RegisteredUser SerialNumber Version --------------- ------------ ----------- -------------- ------------ ------- C:\WINDOWS\system32 19043 Test00 00000-00000-00000-AAOEM 10.0.19043
  • Just the version:
    (Get-CimInstance -ClassName CIM_OperatingSystem).Version 10.0.19043

See also: Returning an exit code from a PowerShell script

0

After updating to the latest version of powershell, the issue was solved.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like