【问题标题】:Foreach try catchForeach 尝试捕获
【发布时间】:2017-09-05 00:11:05
【问题描述】:

我有一个包含计算机列表的文件,我需要遍历该列表并报告其中是否有空闲。

$list = get-content "pathtofile.txt"

foreach ($computer in $list) {
  try {
    quser /server:$computer
  } catch [System.Management.Automation.RemoteException] {
    Write-Host "$computer is free"
  }
}

现在它可以工作了,但我希望捕获错误消息并将其更改为混乱的计算机名称是免费的。

目前它仍在返回

quser : 没有用户存在 * 在行:5 字符:5 + quser /服务器:$计算机 + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (No User exists for *:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError

对于免费的计算机。

我能够通过在我知道是免费的计算机上运行quser 命令然后运行$Error[0] | fl * -Force 来获得$Error[0] | fl * -Force

写错误流:真 PSMessage详细信息: 异常:System.Management.Automation.RemoteException:没有用户存在 * TargetObject : 没有用户存在 * CategoryInfo : NotSpecified: (No User exists for *:String) [], RemoteException FullyQualifiedErrorId : NativeCommandError 错误详情 : InvocationInfo : System.Management.Automation.InvocationInfo ScriptStackTrace:在,:第 1 行 管道迭代信息:{0, 0}

这给了我异常代码。

现在我确实查看了Foreach error handling in Powershell,这表明我的代码应该是正确的,所以不确定为什么 catch 不起作用。

【问题讨论】:

    标签: powershell


    【解决方案1】:
    try {
        $savePreference = $ErrorActionPreference
        $ErrorActionPreference = 'Stop'
        quser /server:$computer 2>&1
    }
    
    catch [System.Management.Automation.RemoteException] {
        Write-Host "$computer is free"
    }
    
    finally
    {
        $ErrorActionPreference = $savePreference
    }
    

    【讨论】:

      【解决方案2】:

      我通常这样做:

      $list = get-content "pathtofile.txt"
      
      foreach ($computer in $list)
      {
          try 
      {
          quser /server:$computer
      }
      catch
      {
          if ($Error.Exception -eq "System.Management.Automation.RemoteException: No User exists for *")
          {
              Write-Host "$computer is free"
          }
          else
          {
              throw $error
          }
      }
      

      }

      【讨论】:

        猜你喜欢
        • 2019-08-25
        • 2017-09-12
        • 1970-01-01
        • 2010-09-12
        • 1970-01-01
        • 2011-08-23
        • 2011-03-25
        • 1970-01-01
        • 2013-07-12
        相关资源
        最近更新 更多