【问题标题】:Checking exit code of last command using "if" statement使用“if”语句检查最后一个命令的退出代码
【发布时间】:2017-11-10 17:52:58
【问题描述】:

我想检查最后一条命令的状态,并根据退出代码,进一步执行命令。

最后执行的命令是:

$hiveJob = Start-AzureHDInsightJob -Cluster $clusterName -JobDefinition  $hiveJobDefinition
Wait-AzureHDInsightJob -Job $hiveJob -WaitTimeoutInSeconds 5400
Get-AzureHDInsightJobOutput -Cluster $clusterName -JobId $hiveJob.JobId -StandardOutput

输出是:

Cluster         : crmhdinsight  
ExitCode        : 0  
Name            : Hive: show tables;  
PercentComplete :   
Query           : show tables;  
State           : Completed  
StatusDirectory : 7dc4b67f-99a9-4c6b-a9f3-ffe8b4e29c7e  
SubmissionTime  : 7/28/2014 11:44:04  
AMJobId         : job_1406103802152_0053  

现在,我只想在退出代码为零时执行更多命令。如何针对这种情况编写if 语句?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您在谈论“退出代码”。如果你的意思是$LastExitCodeautomatic variable,它只会在你调用windows程序时填充,例如RAR:

    $x=rar
    $LastExitCode
    

    它将返回退出代码 7(如果您安装了 RAR)。

    但是,cmdlet 不填充此变量。您可以为此使用另一个自动变量$?

    $x=gci
    $?
    

    如果命令成功完成,它只会给出$True,如果有错误,它只会给出$False

    【讨论】:

      【解决方案2】:

      来自 Get-Help about_If:

      语法 以下示例显示了 If 语句的语法:

         if (<test1>)
             {<statement list 1>}
         [elseif (<test2>)
             {<statement list 2>}]
         [else
             {<statement list 3>}]
      

      注意:elseif 和 else 两边的方括号表示它们是可选的。

      将返回的对象赋值给一个变量:

      $hiveJob = Start-AzureHDInsightJob -Cluster $clusterName -JobDefinition  $hiveJobDefinition
      Wait-AzureHDInsightJob -Job $hiveJob -WaitTimeoutInSeconds 5400
      $Result = Get-AzureHDInsightJobOutput -Cluster $clusterName -JobId $hiveJob.JobId -StandardOutput
      

      然后

      if ($Result.ExitCode -eq 0)
        {
          #More commands
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-26
        • 2014-12-27
        • 2020-04-21
        • 1970-01-01
        • 2013-09-14
        • 1970-01-01
        • 1970-01-01
        • 2012-10-11
        相关资源
        最近更新 更多