What is the use of $Lastexitcode and $? Variable in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

$LastExitCode in Powershell is the number that represents the exit code/error level of the last script or application executed and $? (Dollar hook) also represents the success or the failure of the last command. In general, both represent the same but the output method is different. The first command output is in the Number format (0 and 1) and the latter command is for Boolean (True or False) output.

For example,

PS C:\WINDOWS\system32> $LASTEXITCODE
0
PS C:\WINDOWS\system32> $?
True

As you see the output, 0 represents the success status of the $LastExitCode command and $True for the $?.

Now if the command doesn’t run successfully then what output you will get for both the commands. Check the below example.

PS C:\WINDOWS\system32> ping anyhost.test
Ping request could not find host anyhost.test. Please check the name and try
again.
PS C:\WINDOWS\system32> $LASTEXITCODE
1
PS C:\WINDOWS\system32> $?
True

And you terminate the output of any command in the middle of execution, $lastexitcode will be different but $? command output will be true as the command exists and it can resolve the domain.

PS C:\WINDOWS\system32> ping google.com

Pinging google.com [172.217.166.174] with 32 bytes of data:
Reply from 172.217.166.174: bytes=32 time=30ms TTL=55

Ping statistics for 172.217.166.174:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 30ms, Maximum = 30ms, Average = 30ms
Control-C
PS C:\WINDOWS\system32> $LASTEXITCODE
-1073741510
PS C:\WINDOWS\system32> $?
True
raja
Published on 27-May-2020 09:22:05
Advertisements