2015-08-20 10 views
7

In uno script mi ​​è stato mostrato oggi era la linea:

If ($?) { 
#do some stuff 
} 

non ho mai visto il segno del dollaro del punto interrogativo alias $? prima e non sono in grado di accertare tramite Google a cosa serve.

Quando lo eseguo in una finestra di PowerShell in genere restituisce True, tuttavia occasionalmente restituisce False. I miei test sembravano suggerire che restituisce False quando il codice che lo precede viene eseguito in un errore (e nel contesto del copione che ho visto in questo potrebbe avere senso) quindi questo è forse un modo alternativo per gestire un TRY .. CATCH scenario.

Esempio:

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 

chiunque possa verificare per me se questo è il caso o se serve qualche altro scopo?

risposta

11

Da about_automatic_variables:

$?
Contiene lo stato di esecuzione dell'ultima operazione. Contiene TRUE se l'ultima operazione è riuscita e FALSE se non è riuscita.

Get-Help about_automatic_variables 
+0

Grazie per quel post Ansgar – Jimbo