此脚本的所需结果是在主机列表中找到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
答案 0 :(得分:1)
只需将该调用的ErrorAction
设置为stop
:
Invoke-Command -ComputerName "sdf" {$PSVersionTable.PSVersion} -ErrorAction Stop