Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

Windows Powershell 2.0 returns incorrect exit code, when it is a negative number


Symptoms

Consider the following scenario:

  • You use Windows Powershell 2.0 to call a Powershell script that returns a negative exit code.
    Example:
    • To check if a product installation finished successfully or not.
    • If a scheduled task with a Powershell script finished successfully or not.

  • PowerShell 2.0 may not return the correct exit code.

↑ Back to the top


Workaround

To workaround this problem, do not use negative exit codes with Powershell version 2.0.

↑ Back to the top


More Information

==== Sample Script ====

PS C:\temp> gc .\Exit-3.ps1
exit -3

==== Sample Script ====
  • Calling the script from a powershell window
    PS C:\temp> .\Exit-3.ps1
    PS C:\temp> $LastExitCode
    -3
    Note: Calling the script directly from a powershell window - Works as expected !

    As seen below all other calls from powershell or cmd window with –command or –file parameter do not return the right code.
  • Calling the script from a powershell window with parameter –command
    PS C:\temp> powershell -c "c:\temp\Exit-3.ps1"
    PS C:\temp> $LastExitCode
    1
  • Calling the script from a cmd window with parameter –command
    c:\TEMP>powershell -c "c:\temp\Exit-3.ps1"
    c:\TEMP>echo %errorlevel%
    1
  • Calling the script from a cmd window with parameter –file
    c:\TEMP>powershell -f "c:\temp\Exit-3.ps1"
    c:\TEMP>echo %errorlevel%
    65533
  • Calling the script from a powershell window with parameter –file
    PS C:\temp> powershell -f "c:\temp\Exit-3.ps1"
    PS C:\temp> $LastExitCode
    65533

↑ Back to the top


Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the "Applies to" section.

↑ Back to the top


Keywords: kb

↑ Back to the top

Article Info
Article ID : 2646183
Revision : 1
Created on : 1/7/2017
Published on : 8/1/2012
Exists online : False
Views : 78