Powershell 处理远程连接异常

Powershell 处理远程连接异常,powershell,powershell-remoting,Powershell,Powershell Remoting,此脚本的预期结果是在主机列表上查找PowerShell版本。我希望在远程计算机关闭或未启用远程处理时处理异常。但是,捕获似乎没有输入。仅会出现PowerShell发出的标准红色火焰错误消息 我需要做什么来捕获异常 X:\Scripts\PSAutomation> Get-Content .\get-versions.ps1 server_list = @( 'CAPPY' ) $server_list | ForEach-Object { Try {

此脚本的预期结果是在主机列表上查找PowerShell版本。我希望在远程计算机关闭或未启用远程处理时处理异常。但是,
捕获
似乎没有输入。仅会出现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

使用
-ErrorAction
会导致红色消息以正常控制台文本颜色显示。但是,
Write Host
中没有任何内容出现。我认为您错了,消息应该以连接失败开始…这是因为catch块中的$表示错误,而不是当前的foreach对象管道变量。您可能必须在尝试之前引入一个变量,例如:
$current=$\ucode>,并在写主机中使用
$current
而不是
$\ucode>