0

I want to make a small PS script that checks the status of a service logon account against a server list. What i need to do is, if a server is down, it shows a custom error message that tells me which server from the list is offline, instead of the default bulky red error message.

Here is what i came up with so far.

This is the RPC error powershell shows if something wrong with a server.

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 Exception

PS c:\> $Error[0].Exception.GetType().FullName
System.Runtime.InteropServices.COMException

I searched on the internet for a solution, and this is what i came up with at last, but of course not working.

$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"

I'd really appreciate your help

1 Answer 1

2

The error is on Get-WmiObject not Where-Object. And you have to set error action to stop to catch terminating error.

$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"
2
  • Thank you so much Wasif. That worked. I really thought that "-ErrorAction Stop" would stop the script and prevents it from processing the following servers in the list. Jul 8, 2020 at 16:38
  • Welcome! Happy coding
    – Wasif
    Jul 8, 2020 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.