Windows: Get Exit Code (ErrorLevel) – CMD & PowerShell

Every command or application returns an exit status, also known as a return status or exit code.

A successful command or application returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code.

In Linux you can get the exit status of a last command by executing echo $?.

In this article i will show how to get the return code from the last console command or application in Windows using the command-line prompt (CMD) or the PowerShell.

Exit Code Of Last Console Command

Return True or False depending on whether the last console command or application exited without error or not:

# Windows CMD
C:\> if %ErrorLevel% equ 0 (echo True) else (echo False)

# Windows PowerShell
PS C:\> $?

Get the exit code of the last console command or application:

# Windows CMD
C:\> echo %ErrorLevel%

# Windows PowerShell
PS C:\> $LastExitCode

Exit Code Of Windowed Application

Return True or False depending on whether the last windowed application exited without error or not:

# Windows CMD
C:\> start /wait app.exe
C:\> if %ErrorLevel% equ 0 (echo True) else (echo False)

# Windows PowerShell
PS C:\> app.exe
PS C:\> $?

Get the exit code of the windowed application:

# Windows CMD
C:\> start /wait app.exe
C:\> echo %ErrorLevel%

# Windows PowerShell
PS C:\> app.exe
PS C:\> $LastExitCode
Was it useful? Share this post with the world!

4 Replies to “Windows: Get Exit Code (ErrorLevel) – CMD & PowerShell”

  1. This seems good and correct. But I am seeking how to get the exitcode from a PowerShell script run from cmd.exe and the exit code from a Windows executable run from PowerShell.
    C:> powershell -Nologo -NoProfile -File ‘.\ascript.ps1’
    ECHO %ERRORLEVEL%
    PS C:\> & ascript.bat
    $?

    1. Hi Paul , regarding the first case the solution would be closing the ps1 script with this statement
      [Environment]::Exit(7)
      Then the DOS shell will find %errorlevel% equal to 7 .

      Regarding the second case , you have to close the .bat script with
      exit /b 5
      and read variable $LastExitCode in the PS environment

      1. That’s not DOS; DOS doesn’t have the errorlevel environment-variable. See Rob van der Woude’s webpage about Errorlevels. You’re talking about the Windows Command Prompt.

  2. $p = Start-Process .\console.exe -PassThru -Wait
    $p.ExitCode

    -PassThru :- causes Start-Process to returns an object containing information about the executed process.

    -Wait :- causes Start-Process to block and wait for the executable to complete before returing

Leave a Reply