尝试抓住powershell invoke-command

对于使用Powershell的不正确主机,它不会作为调用命令的一部分“捕获”块

$server= @("correcthost","Incorrecthost")
foreach($server in $server)
   {

     Try{
          Invoke-Command -ComputerName $server -ArgumentList $server -ScriptBlock    {

             $serverk=$args[0]    
             write-host $serverk
            }
        }
    Catch
       {
        write-host "error connecting to $serverk"
       }
  }

我希望在我尝试不正确的主机时执行catchblock

但实际输出不是打印捕获块

may0777 回答:尝试抓住powershell invoke-command

有两个问题。首先,变量$serverkcatch块中超出范围。它仅在远程计算机上使用,因此在本地系统上不存在-或没有价值。

调试任何Powershell脚本应始终从打开严格模式开始,这样会生成有关未初始化变量的警告。像这样

Set-StrictMode -Version 'latest'
...<code>
The variable '$serverk' cannot be retrieved because it has not been set.
At line:12 char:41
+         write-host "error connecting to $serverk"
+                                         ~~~~~~~~
    + CategoryInfo          : InvalidOperation: (serverk:String) [],RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

此修复很容易,只需引用$server,它就是迭代$servers时使用的变量。

第二个问题是由ErrorAction引起的,或者是具体的,没有声明一个问题。将-ErrorAction Stop添加到Invoke-Command并像这样在catch块中处理异常,

catch{
    write-host "error connecting to $server`: $_"
}
error connecting to doesnotexist: [doesnotexist] Connecting to remote server doesnotexist failed...
本文链接:https://www.f2er.com/3147487.html

大家都在问