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?
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
来源:https://stackoverflow.com/questions/32120202/what-is-an-alias-for-in-powershell