1

I want to print custom error message in case of error

  Foreach ($server in $servers){
    
     Try{
           $admins = Gwmi win32_groupuser –computer $server
           $admins = $admins |? {$_.groupcomponent –like '*"Administrators"'}
           $admins = $admins |% { $_.partcomponent –match “.+Domain\=(.+)\,Name\=(.+)$” > $nul 
           $matches[1].trim('"') + “\” + $matches[2].trim('"') | Where-Object {$_ -like "$domain*"}}
    
     }
     catch [System.Runtime.InteropServices.COMException]
    {
       
            # You can inspect the error code to see what specific error we're dealing with 
        if($_.Exception.ErrorCode -like "*0x800706BA*")
        {
            # This is instead of the "RPC Server Unavailable" error
             Write-Verbose -Message ('{0} is unreachable' -f $computer) -Verbose 
        }
        else
        {
             Write-Warning $Error[0]
        }
       
    }
     
     # If any other type of Exception is thrown, execute this block
catch [System.Exception]
{
    Write-Error -Message "Some other exception that's nothing like the above examples"
}
     } 

But i'm getting default error

Gwmi : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) At line:4 char:18 $admins = Gwmi win32_groupuser –computer $server

CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

I want to print only names of servers where WMI command fails

I tried this solution but no help

Tried also:

catch [Exception]
{
    if ($_.Exception.GetType().Name -like "*COMException*") {
         Write-Verbose -Message ('{0} is unreachable' -f $computer) -Verbose
    }
}

2 Answers 2

1

Solved, had to specify -erroraction stop on WMI command

0

No to catch errors, you need to set ErrorAction to SilentlyContinue: $admins = Gwmi win32_groupuser –computer $server -ErrorAction SilentlyContinue.

1
  • 1
    How do you then report that the RPC server is unavailable for $server, since that is part of what the asker is trying to do?
    – aaaantoine
    Sep 29, 2021 at 15:14

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.