ErrorLevel equivalent

PowerShell Team

PSMDTAG:FAQ: ErrorLevel – what is the PowerShell equivalent?

In Cmd.exe, %ErrorLevel% is a builtin variable which indicates the success or failure of the last executable run.

In PowerShell, we support:

       Contains True if last operation succeeded and False otherwise.

       Contains the exit code of the last Win32 executable execution.

PS> 2+2
PS> $?
PS> 3/$null
Attempted to divide by zero.
At line:1 char:3
+ 3/$ <<<< null
PS> $?
PS> ping localhost

Pinging [::1] from ::1 with 32 bytes of data:

Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms

Ping statistics for ::1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms
PS> $lastexitcode
PS> ping asdfasdf
Ping request could not find host asdfasdf. Please check the name and try again.
PS> $lastexitcode


Jeffrey Snover [MSFT]
Windows PowerShell/Aspen Architect
Visit the Windows PowerShell Team blog at:
Visit the Windows PowerShell ScriptCenter at:


PSMDTAG:ERROR: %ErrorLevel% , $? and $LastExitCode