PowerShell

PowerShell Last Operation Status Variable: $?

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.

1.PNG

Interesting. The default value seems to be true.

To verify that, I execute the following code:


$? -eq $true

1.PNG

Performing a ping to sid-500.com will not change anything, the value of $? is still true.


Test-Connection sid-500.com -Count 1

1.PNG

$? (False)

Now let’s generate an error and see what $? will tell us.


Test-Connection sid-500.eu -Count 1

1.PNG

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}

1.PNG

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

1.PNG

See you again next time with PowerShell!

Categories: PowerShell

Tagged as: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.