尝试,抓住powershell invoke-command

问题描述 投票:0回答:1

不会使用powershell为不正确的主机“捕获”块作为invoke-command的一部分

$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在我尝试不正确的主机时得到执行

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

powershell try-catch invoke-command
1个回答
1
投票

有两个问题。首先,变量$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...
© www.soinside.com 2019 - 2024. All rights reserved.