【问题标题】:Check if a command has run successfully检查命令是否运行成功
【发布时间】:2020-02-02 00:45:27
【问题描述】:

我尝试在 if 语句中包含以下内容,以便在成功时执行另一个命令:

Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" | Foreach-Object {
        $Localdrives += $_.Path

但我不知道该怎么做。我什至尝试创建一个函数,但我也不知道如何检查该函数是否已成功完成。

【问题讨论】:

    标签: powershell if-statement


    【解决方案1】:

    试试 $?自动变量:

    $share = Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'"
    
    if($?)
    {
       "command succeeded"
       $share | Foreach-Object {...}
    }
    else
    {
       "command failed"
    }
    

    来自about_Automatic_Variables

    $?
       Contains the execution status of the last operation. It contains
    TRUE if the last operation succeeded and FALSE if it failed.
    ...
    
    $LastExitCode
       Contains the exit code of the last Windows-based program that was run.
    

    【讨论】:

    • 这次我选择了第一个解决方案,但这绝对是一个很好的方法。再次感谢谢伊:)
    • Sorry Shay : 测试 get-WmiObject -Class Win32_Share -Filter "Description='glurp'" ,但在这种情况下 $?是真实的,与此描述没有任何共同之处。
    • 命令没有返回错误所以 $?设置为 $true。这与:dir *.NoSucheExtension 相同,结果为空,不被视为错误。当您想测试命令是否返回任何结果时,请使用@JPBlanc 的解决方案。
    • 这应该是公认的答案,因为它与一般问题更相关
    • PS新手问题:"command succeeded"是否与Write-Output "command succeeded"相同(或其他Write-*命令)?
    【解决方案2】:

    你可以试试:

    $res = get-WmiObject -Class Win32_Share -Filter "Description='Default share'"
    if ($res -ne $null)
    {
      foreach ($drv in $res)
      {
        $Localdrives += $drv.Path
      }
    }
    else
    {
      # your error
    }
    

    【讨论】:

      【解决方案3】:

      或者,如果失败没有返回标准输出,则适用于 if 语句:

      if (! (Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'")) { 
        'command failed'
      }
      

      现在还有符号“||”在 powershell 7 中:

      Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" || 'command failed'
      

      【讨论】:

        【解决方案4】:

        在某些情况下,任何选项都是最合适的。这是另一种方法:

        try {
        Add-AzureADGroupMember -ObjectId XXXXXXXXXXXXXXXXXXX -RefObjectId (Get-AzureADUser -ObjectID "XXXXXXXXXXXXXX").ObjectId  -ErrorAction Stop
        Write-Host "Added successfully" -ForegroundColor Green
        $Count = $Null
        $Count = 1
        }
        catch {
        $Count = $Null
        $Count = 0
        Write-Host "Failed to add: $($error[0])"  -ForegroundColor Red
        }
        

        使用 try 和 catch,不仅会在失败时返回错误消息,还会将 $count 变量分配为数字 0。当命令成功时,您的 $count 值会返回 1。此时,您使用此变量值来确定接下来会发生什么。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-02-09
          • 2012-09-21
          • 1970-01-01
          • 1970-01-01
          • 2012-08-06
          • 2017-11-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多