Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `$?` in Powershell?

Tags:

powershell

What is the meaning of $? in Powershell?


Edit: TechNet answers in tautology, without explaining what 'succeed' or 'fail' mean.

$?
Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

I presumed $? would simply test whether $LastExitCode is 0, but I found a counter example where $? is False but $LastExitCode is True.

like image 798
Colonel Panic Avatar asked May 17 '12 10:05

Colonel Panic


People also ask

What does $_ mean in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

What does @() mean in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.

What is $() in PowerShell?

$() is a special operator in PowerShell commonly known as a subexpression operator. It is used when we have to use one expression within some other expression. For instance, embedding the output of a command with some other expression.


3 Answers

It returns true if the last command was successful, else false.

However, there are a number of caveats and non-obvious behaviour (e.g. what exactly is meant by "success"). I strongly recommend reading this article for a fuller treatment.

For example, consider calling Get-ChildItem.

PS> Get-ChildItem 

PS> $? 
    True

$? will return True as the call to Get-ChildItem succeeded.

However, if you call Get-ChildItem on a directory which does not exist it will return an error.

PS> Get-ChildItem \Some\Directory\Which\Does\Not\Exist
    Get-ChildItem : Cannot find path 'C:\Some\Directory\Which\Does\Not\Exist' because it does not exist.

PS> $?
    False

$? will return False here, as the previous command was not successful.

like image 190
RB. Avatar answered Oct 09 '22 17:10

RB.


$? will contain $false if the last command resulted in an error. It will contain $true if it did not. In the PowerShell v1 days, this was a common way to do error handling. For example, in a script, if you wanted to check for the existence of a file and then print a custom message if it did not, you could do:

Get-Item -Path john -ErrorAction silentlycontinue;
if( -not $?)
{
    'could not find file.';
     exit
 }`
like image 22
John Cravener Avatar answered Oct 09 '22 17:10

John Cravener


You can also access last commands exit code using $LastExitCode parameter.

# run some command
# ...
if ((! $?) -and $ErrorAction -eq "Stop") { exit $LastExitCode }
like image 2
Kerem Demirer Avatar answered Oct 09 '22 16:10

Kerem Demirer