What is `$?` in Powershell?

后端 未结 4 741
北荒
北荒 2020-12-01 15:22

What is the meaning of $? in Powershell?


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

相关标签:
4条回答
  • 2020-12-01 15:57

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

    # run some command
    # ...
    if ((! $?) -and $ErrorAction -eq "Stop") { exit $LastExitCode }
    
    0 讨论(0)
  • 2020-12-01 15:59

    $? 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
     }`
    
    0 讨论(0)
  • 2020-12-01 16:14

    I have encountered in Windows Server 2019, $? can be set false when Standard Error has been generated. In my example docker-compose logs warnings via Standard Error, so although exiting with 0, $? indicates failure.

    0 讨论(0)
  • 2020-12-01 16:24

    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.

    0 讨论(0)
提交回复
热议问题