此脚本的预期结果是找出主机列表上的 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
我实际上遇到过非常类似的情况,我有一长串电脑,但有些离线,有些我无法访问。此外,还有一些我did可以访问的内容,会遇到“无法初始化驱动器”的非终止错误。我使用 Invoke-Command 中的 -ErrorVariable 参数将每个 Invoke-Command 遇到的任何错误保存到变量中(我将其称为 $stoperror)。这是我的代码片段的简化版本:
$computers = get-content $(Read-Host "enter path list .txt file")
foreach ($computer in $computers) {
$query_result = invoke-command -computername $computer -errorvariable stoperror -scriptblock {
Write-Host "Accessed $env:COMPUTERNAME" -ForegroundColor Green
}
if (($stoperror -like "*Access is denied*") -or ($stoperror -like "*WinRM cannot complete the operation*")) {
write-host $stoperror
Write-Host "$computer got an access denied or winrm operation error!" -ForegroundColor Yellow
}
棘手的部分是当您使用 -errorvariable 参数并定义变量时,您不必使用 $.如果这有帮助,请告诉我。