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.
And

    $LASTEXITCODE
       Contains the exit code of the last Win32 executable execution.

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

Pinging jpsvista1.ntdev.corp.microsoft.com [::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
0
PS> ping asdfasdf
Ping request could not find host asdfasdf. Please check the name and try again.
PS> $lastexitcode
1

 

Jeffrey Snover [MSFT]
Windows PowerShell/Aspen 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

 

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

0 comments

Discussion is closed.

Feedback usabilla icon