我想做一个小的PS脚本,根据服务器列表检查服务登录帐户的状态。我需要做的是,如果服务器关闭,它会显示一条自定义的错误消息,告诉我列表中的哪一台服务器离线,而不是默认的红色错误消息。
这是我到目前为止想出来的。
如果服务器出了问题,powershell会显示以下RPC错误。
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At V:\HRG01\MPE_HRG01_Information-Technology\Share\ITSS-Core\Icinga Monitor Software\Service Check\Get-Service Log On.ps1:1 char:1
+ Get-WmiObject win32_service -ComputerName (Get-Content -path ".\serverlist.txt") ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
PS异常
PS c:\> $Error[0].Exception.GetType().FullName
System.Runtime.InteropServices.COMException
我在互联网上寻找解决方案,这是我最终想出来的,但当然不起作用。
$servers= Get-Content -path ".\serverlist.txt"
foreach ($server in $servers)
{
try {
Get-WmiObject win32_service -ComputerName $server |
Where-Object {$_.Name -eq "icinga2"} -ErrorAction Continue |
format-list -Property PSComputerName,Name,StartName
}
catch [System.Runtime.InteropServices.COMException]
{
Write-Host "ERROR: $Server connection error"
}
}
Tee-Object .\Results.txt -Append
Read-Host -Prompt "Press Enter to exit"
我真的很感谢你的帮助
发布于 2020-07-09 00:13:21
错误出现在Get-WmiObject
上,而不是Where-Object
上。并且您必须将错误操作设置为停止,以捕获终止错误。
$servers= Get-Content -path ".\serverlist.txt"
foreach ($server in $servers)
{
try {
Get-WmiObject win32_service -ComputerName $server -ErrorAction Stop |
Where-Object {$_.Name -eq "icinga2"} |
format-list -Property PSComputerName,Name,StartName
}
catch [System.Runtime.InteropServices.COMException]
{
Write-Host "ERROR: $Server connection error"
}
}
Tee-Object .\Results.txt -Append
Read-Host -Prompt "Press Enter to exit"
https://stackoverflow.com/questions/62798955
复制相似问题