Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is $? an alias for in Powershell?

Within a script I was shown today was the line:

If ($?) {
#do some stuff
}

I have never seen the dollar sign question mark alias $? before and am unable to ascertain via Google what it is for.

When I execute it in a powershell window it typically returns True, however occasionally returns False. My testing seemed to suggest that it returns False when the code that precedes it executes in an error (and within the context of the script I saw it in this might make sense) so this is perhaps an alternative way to handle a TRY.. CATCH scenario.

Example:

PS C:\Users\me> $?
True
PS C:\Users\me> $?
True
PS C:\Users\me> blah
blah : The term 'blah' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ blah
+ ~~~~
+ CategoryInfo          : ObjectNotFound: (blah:String) [],         CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

PS C:\Users\me> $?
False
PS C:\Users\me> $?
True

Can anyone verify for me if this is the case or if it serves some other purpose?

like image 635
Mark Wragg Avatar asked Aug 20 '15 13:08

Mark Wragg


People also ask

What does $? Mean in PowerShell?

$? Contains the execution status of the last command. It contains True if the last command succeeded and False if it failed. For cmdlets and advanced functions that are run at multiple stages in a pipeline, for example in both process and end blocks, calling this.

What is alias used for in PowerShell?

An alias is an alternate name or nickname for a cmdlet or for a command element, such as a function, script, file, or executable file. You can use the alias instead of the command name in any PowerShell commands.

How do I set an alias in PowerShell?

PowerShell includes built-in aliases that are available in each PowerShell session. The Get-Alias cmdlet displays the aliases available in a PowerShell session. To create an alias, use the cmdlets Set-Alias or New-Alias . In PowerShell 6, to delete an alias, use the Remove-Alias cmdlet.

How do I add an alias to my PowerShell profile?

To create an alias for a command, create a function that includes the command, and then create an alias to the function. To save the aliases from a session and use them in a different session, add the Set-Alias * command to your Windows PowerShell profile.


1 Answers

From about_automatic_variables:

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

Get-Help about_automatic_variables
like image 193
boeprox Avatar answered Oct 14 '22 21:10

boeprox