处理远程连接异常

时间:2016-09-27 20:06:53

标签: powershell powershell-remoting

此脚本的所需结果是在主机列表中找到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

1 个答案:

答案 0 :(得分:1)

只需将该调用的ErrorAction设置为stop

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