【问题标题】:PowerShell Remoting - Invoke-Command not Returning OutputPowerShell 远程处理 - 调用命令不返回输出
【发布时间】:2017-04-19 13:01:45
【问题描述】:

我正在管理员模式下从 PowerShell 远程运行以下命令。这会从远程机器获取应用程序池(在 IIS 中)的状态。

$result = Invoke-Command -ComputerName $servername -ScriptBlock {
    param($appPoolName) 
    Get-WebAppPoolState -Name $appPoolName
} -ArgumentList $appPoolName | select value

如果我传递了正确的值,我将在 $result 中获得正确的数据,但如果我传递了无效的服务器名称,则会出现以下错误。

“连接到远程服务器失败并显示以下错误消息:WinRM 无法处理请求。”

问题是我在$result 中没有得到任何东西,即使这也不会阻止 Catch。无法确定命令是否成功运行。

请提供有关如何在 $result 中获取命令输出的任何指示。

注意:我是远程机器上的管理员,并且已启用 WinRM。

【问题讨论】:

    标签: powershell remoting invoke-command


    【解决方案1】:

    为了捕捉错误,它需要终止。您可以使用-ErrorAction Stop 强制执行此操作。

    try {
        $result = Invoke-Command -ComputerName $servername -ScriptBlock {
            param($appPoolName) 
            Get-WebAppPoolState -Name $appPoolName
        } -ArgumentList $appPoolName -ErrorAction Stop | select value
    }
    catch {
        $result = [pscustomobject]@{"value"="Not Found"}
    }
    

    【讨论】:

      【解决方案2】:

      通过添加 -ErrorAction Stop 使用 try/catch 捕获错误并使用 $error[0] 显示最后一个错误

      Try{
          $result = Invoke-Command -ComputerName $servername -ErrorAction Stop -ScriptBlock {
              param($appPoolName) 
              Get-WebAppPoolState -Name $appPoolName
          } -ArgumentList $appPoolName | Select-Object value
      }
      Catch{
          $result = $error[0]
      }
      

      【讨论】:

        猜你喜欢
        • 2018-10-31
        • 2018-05-16
        • 2018-12-04
        • 2016-03-10
        • 1970-01-01
        • 2011-06-04
        • 2014-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多