Welcome to MSDN Blogs Sign in | Join | Help

Windows PowerShell Exit Codes

Windows PowerShell Exit Codes

 

PSMDTAG:FAQ: How can my script control the PowerShell exit code?

Answers:

1.      A normal termination will set the exitcode to 0

2.      An uncaught THROW will set the exitcode to 1

3.      The EXIT statement will stop the process and set the exitcode to whatever is specified.

 

c:\>powershell -noprofile -command "Write-output Test"
Test

c:\>echo %errorlevel%
0

c:\>powershell -noprofile -command "Write-output Test; throw 'ERROR'"
Test
ERROR
At line:1 char:25
+ Write-output Test; throw  <<<< 'ERROR'


c:\>echo %errorlevel%
1

c:\>powershell -noprofile -command "Write-output Test; exit 31492"
Test

c:\>echo %errorlevel%
31492

 

Jeffrey Snover [MSFT]
Windows PowerShell/MMC Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at
http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

 

 

Published Saturday, October 14, 2006 11:10 PM by PowerShellTeam
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Windows PowerShell Exit Codes

I love the new code markup---one issue though: in IE7 RSS reader the markup CSS is visible at the top of the story, in a huge block. As a web page the blog entry appears fine however.

Sunday, October 15, 2006 12:01 AM by Vivek

# re: Windows PowerShell Exit Codes

I was wondering how can I check exit code from a PS script.

# filename: tp.ps1

$s = get-service | select-object Name, status

$b = $False

foreach ($i in $s)

{

       # Check foe Exchange store service.

       # Misspelled service name.

if ( $i.name -eq "MSExchangeI")

{$b = $True}

}

if ($b -eq $True)

{exit 0}

else

{exit 99}

# tp.ps1 ends

I called this script from cmd.exe as follows.

Powershell C:\ts.ps1

echo %errorlrvel%

This prints 1 to console and not 99. What am I doing wrong here?

Wednesday, January 24, 2007 10:27 AM by mdexch

# re: Windows PowerShell Exit Codes

Hi

I have the same problem.....

Have anyone found an solution for this problem???

Monday, April 30, 2007 7:25 AM by cbr

# re: Windows PowerShell Exit Codes

Try running the script like this:

PowerShell –Command “& { c:\ts.ps1; exit $LASTEXITCODE}”

echo %errorlevel% - Should show what the ps1 script exited with.

Thursday, June 07, 2007 12:50 AM by alemyis

# re: Windows PowerShell Exit Codes

Monday, July 16, 2007 8:14 PM by Joel "Jaykul" Bennett

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker