Powershell always exiting with exit code 1
(Continuing from my comment)
These are two completely separate things:
-
This is just using> type test.ps1 Write-Host testing > echo %ERRORLEVEL% 0
Get-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.exe
fromcmd.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