不会使用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在我尝试不正确的主机时得到执行
但是实际输出不是打印捕获块
有两个问题。首先,变量$serverk
在catch
块中超出范围。它仅在远程计算机上使用,因此在本地系统上不存在-或没有价值。
调试任何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...