Powershell 如何在此脚本中插入错误操作以静默方式继续?

Powershell 如何在此脚本中插入错误操作以静默方式继续?,powershell,Powershell,我正在尝试在此脚本中插入一个错误操作,以便它发现任何处于脱机状态且无法查询的计算机在检查其windows版本之前,都会先告诉我它处于脱机状态 然后在检查完所有机器后停止 $machinesv = Get-Content -Path C:\Users\khalifam\Desktop\WinverMachines.txt foreach ($Computer in $machinesv ) { Invoke-Command -Computername $machinesv -Script

我正在尝试在此脚本中插入一个错误操作,以便它发现任何处于脱机状态且无法查询的计算机在检查其windows版本之前,都会先告诉我它处于脱机状态

然后在检查完所有机器后停止

$machinesv = Get-Content -Path C:\Users\khalifam\Desktop\WinverMachines.txt

foreach ($Computer in $machinesv ) {
    Invoke-Command -Computername $machinesv -Scriptblock {
        (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName" -Name ComputerName).ComputerName 
        (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseID).ReleaseID 
    }
} 
输出:

LN-T48-PF11LK59 1809 LN-T48-PF11LK5U 1809 LN-T48-PF11LK6W 1809 [LN-T48-PF11LK6E] Connecting to remote server LN-T48-PF11LK6E failed with the following error message : The WinRM client cannot process the request because the server name cannot be resolved. For more information, see the about_Remote_Troubleshooting Help topic. + CategoryInfo : OpenError: (LN-T48-PF11LK6E:String) [], PSRemotingTransportException + FullyQualifiedErrorId : ComputerNotFound,PSSessionStateBroken LN-T48-PF11LDQ1 1809 LN-T48-PF11LK59 1809 LN-T48-PF11LK5U 1809 LN-T48-PF11LK6W 1809 [LN-T48-PF11LK6E]连接到远程服务器LN-T48-PF11LK6E失败,原因是 以下错误消息:WinRM客户端无法处理该请求,因为 无法解析服务器名称。有关更多信息,请参阅 关于远程故障排除帮助主题。 +CategoryInfo:OpenError:(LN-T48-PF11LK6E:String)[],PSRemotingTransportException +FullyQualifiedErrorId:找不到计算机,PSSessionStateBreaked LN-T48-PF11LDQ1 1809
如果您的唯一目标是在调用命令之前测试连接性,那么您应该在循环中调用该命令之前检查状态:

#requires -PSEdition Desktop
foreach ($cn in ...) {
    if (Test-Connection -ComputerName $cn) { ... }
    else { continue }
}

我知道这是一种不好的做法,但您可以使用-ErrorAction Stop将Invoke命令放在try/catch块中,因为我认为Invoke命令的默认错误不会终止。或者,您可以使用测试连接来查看计算机是否可以事先联系:)有两种方法会出现在您的脑海中。。。[1] 在
Invoke命令
[2]之前测试“是否可以访问”,删除循环,将
Invoke命令
设置为SilentlyContinue on errors,为I-C cmdlet提供整个系统列表,然后通过比较输入列表和响应者列表来派生非响应者。//第二个比第一个快得多。[咧嘴笑]