处理远程连接异常

问题描述:

此脚本的预期结果是找出主机列表上的PowerShell版本。我想在远程机器关闭或未启用远程处理时处理异常。但是,似乎没有输入catch。出现PowerShell的标准红色火焰错误消息。处理远程连接异常

我需要做什么来捕捉异常?

X:\Scripts\PSAutomation> Get-Content .\get-versions.ps1 
server_list = @(
    'CAPPY' 
) 

$server_list | 
    ForEach-Object { 
     Try { 
      Invoke-Command -ComputerName $_ {$PSVersionTable.PSVersion} 
     } 
     Catch 
     { 
      Write-Host "Failed to connect to $_" 
     } 
    } 
X:\Scripts\PSAutomation> .\get-versions.ps1 
[CAPPY] Connecting to remote server CAPPY failed with the following error message : WinRM cannot process the 
request. The following error occurred while using Kerberos authentication: Cannot find the computer CAPPY. Verify 
that the computer exists on the network and that the name provided is spelled correctly. For more information, see 
the about_Remote_Troubleshooting Help topic. 
    + CategoryInfo   : OpenError: (CAPPY:String) [], PSRemotingTransportException 
    + FullyQualifiedErrorId : NetworkPathNotFound,PSSessionStateBroken 

只需设置ErrorAction为呼叫stop

Invoke-Command -ComputerName "sdf" {$PSVersionTable.PSVersion} -ErrorAction Stop 
+0

使用'-ErrorAction'使红色消息出现在正常控制台文本颜色。但是,没有任何关于'Write-Host'的信息出现。 – lit

+0

我认为你错了,消息应该以连接失败开始......那是因为你的catch块中的$ _代表错误而不是当前的foreach对象管道变量。您可能必须在尝试之前引入一个变量,例如:'$ current = $ _'并在您的写主机中使用'$ current'而不是'$ _' –

+0

是的。你是对的。我应该看到它。 – lit