How to create Powershell custom error output?

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

powershell
error-handling

1 Answer

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"
answered on Stack Overflow Jul 8, 2020 by programmer365

User contributions licensed under CC BY-SA 3.0