Automating the world one-liner at a time…
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+24PS> $?TruePS> 3/$nullAttempted to divide by zero.At line:1 char:3+ 3/$ <<<< nullPS> $?FalsePS>PS> ping localhost
Pinging jpsvista1.ntdev.corp.microsoft.com [::1] from ::1 with 32 bytes of data:
Reply from ::1: time<1msReply from ::1: time<1msReply from ::1: time<1msReply 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 = 0msPS> $lastexitcode0PS> ping asdfasdfPing request could not find host asdfasdf. Please check the name and try again.PS> $lastexitcode1
Jeffrey Snover [MSFT]Windows PowerShell/Aspen ArchitectVisit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShellVisit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx
PSMDTAG:ERROR: %ErrorLevel% , $? and $LastExitCode
Can we change the value in lastexitcode ?
is this a read only attribute
$LASTEXITCODE seems to behave differently on Vista than on Windows Server 2008 for PowerShell script calls.
When I invoke a PowerShell script on Vista, both $? and $LASTEXITCODE seem to be set on return from the script. That is, if $? is True, then $LASTEXITCODE will be 0. If $? is False, then $LASTEXITCODE will be non-zero.
For script invocations on W2K8, it appears as if $LASTEXITCODE will be set iff the invoked script returns via an exit command. Otherwise, $LASTEXITCODE may be null.
Is this a feature? Is $LASTEXITCODE only supposed to be set by executables (including cmd.exe)? Is $? useful for testing the success or failure of PowerShell scripts?
Just to comment on Sung's issue - you could always get both variables in one statement like:
$returncode = $?+":"+$lastexitcode;
$codearr = $returncode.split(":");
write-host $codearr[0];
write-host $codearr[1];
I'm a noob with PowerShell but I thought this might work.
Quote:
$LASTEXITCODE would be a good name for a film about a burnt out techie who writes a powershell script that embezzles trillions of dollars out of a bank.
Tuesday, October 03, 2006 4:09 AM by lb
HA HA HA that is so funny.