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
0when the script ran successfully, and when I run this on my own machine, or any server outside of this customer, the exitcode is0:> 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?
12 Answers
(Continuing from my comment)
These are two completely separate things:
This is just using> type test.ps1 Write-Host testing > echo %ERRORLEVEL% 0Get-Content(if you were in the PowerShell console, notcmd.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
- thus command being run here is
> powershell -NoProfile -NonInteractive -NoLogo ./test.ps1 testing > echo %ERRORLEVEL% 1- This is actually running the script, by calling
powershell.exefromcmd.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, notCMD.exe/DOS stuff.
- This is actually running the script, by calling
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
0After updating to the latest version of powershell, the issue was solved.