The $LASTEXITCODE variable returns a code that tells you whether the last operation was successful or not. There’s another variable that is similiar and it is called $?. $? tells us if something is true or false but it doesn’t tell us any code number like $LASTEXITCODE does. In this blog post I will carry out some actions and will bring light into the darkness of $?. Are you ready? Let’s jump in.
This time I will use PowerShell 7, don’t worry if you are using Windows PowerShell, the functionality is the same.
$? (True)
After I started PowerShell, I run $? to see what’s gonna happen.
Interesting. The default value seems to be true.
To verify that, I execute the following code:
$? -eq $true
Performing a ping to sid-500.com will not change anything, the value of $? is still true.
Test-Connection sid-500.com -Count 1
$? (False)
Now let’s generate an error and see what $? will tell us.
Test-Connection sid-500.eu -Count 1
Fine. That’s it. Or not? It’s not the end of the story there is something more to say.
The Trap – Scriptblocks
The following code doesn’t make sense, it’s more meaningful without Invoke-Command, but good for demonstration. $? returns True or False, but only from the command itself, not from the script block, so the value is True here, because the scriptblock generates the error, not Invoke-Command.
Invoke-Command -ScriptBlock {Get-ChildItem -Path C:\NotExist}
Don’t mix up
Remember that $? returns false only if an error occured, but not if the result is true or false. See the example below where the execution status of Cmdlet returns false but no error and therefore $? is true. So don’t mix up two things: errors and boolean values.
Test-Path -Path C:\NotExist
See you again next time with PowerShell!
Categories: PowerShell
Thanks for this tip!
Best wishes Marc
LikeLiked by 1 person