sapo980
sapo980

Reputation: 23

Powershell exit status

what's the powershell equivalent of simply:

bash test.sh

I'd like to call a powershell script (from outside a powershell environment) and be able to get a return value of 0 if it executed successfully, and otherwise a non-zero value if either:

And then, how to access this return value, which in linux would be

echo $?

Upvotes: 2

Views: 10254

Answers (3)

Joey
Joey

Reputation: 354506

Simply using

powershell -file foo.ps1

should work:

C:\>set PATH=
C:\>powershell -file Untitled1.ps1
'powershell' is not recognized as an internal or external command,
operable program or batch file.
C:\>echo %errorlevel%
9009

C:\>powershell -File not-there.ps1
The argument 'not-there.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
C:\>echo %errorlevel%
-196608

C:\>powershell -file exitcode.ps1
C:\>echo %errorlevel%
1337

Upvotes: 1

jurgenb
jurgenb

Reputation: 472

In cmd you can use the %ERRORLEVEL% variable to check for any error code returned by the last command. If this was incorrect or not found this will be different from zero. This will already take care of the first 2 cases, where powershell.exe is not found or the script can't be found.

To return an errorcode from a powershell script use the exit <errorcode> statement.

You can check this in PS using the $LASTEXITCODE variable. To return this into your calling batch process, you can use the following structure:

powershell.exe -noprofile -command ". c:\t\returnCode.ps1 ; exit $LASTEXITCODE "
if %errorlevel%==0 (echo "yep") else (echo "nope")

Where the returncode.ps1 script is like:

# do stuff
exit 1234

Upvotes: 1

Bali C
Bali C

Reputation: 31231

Provided you can modify the powershell script, you can set the exit code using:

[Environment]::Exit(yourexitcode)

Then read the last exit code with whatever app you are calling it from.

Upvotes: 0

Related Questions