mipnix
mipnix

Reputation: 211

Write custom error to log on RPC server unavailable

I want to output a custom error message to a log, when a GWMI query fails. I can catch the exception, but apparently only the last one, because the output in my error file only has the name of the last computer in the list. I am using a list of computers I know do not have WMI enabled. There should be an entry for each one.

I have a list of domain computers in a text file, each on a single line, no trailing characters. I loop through the file to get network information, using GWMI. Some of the computers do not have WMI enabled, and I want to know which ones. My current script just throws a:

gwmi : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:12 char:17
+         $base = gwmi win32_networkadapterconfiguration -computername $comp | whe ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId :        GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand   

whenever it loops through a machine that does not have wmi enabled.

This does not identify the computer that threw the exception. What I would like is for every time the RPC server is unavailable... error is thrown, for a custom error message to be written to a log with the name of the computer that threw the exception.

My script:

$computers = Get-Content -path f:\scripts\docs\computer_list_test.txt

if (F:\scripts\wmi_mac_output.txt){
rm F:\scripts\wmi_mac_output.txt
}

foreach ($comp in $computers) {

try
{

    $base = gwmi win32_networkadapterconfiguration -computername $comp -ErrorAction Stop | where {$_.dnsdomain -eq "mydomain.com"}
    $machine = $base.DNSHostName 
    $mac = $base.MACAddress
    $ip = $base.IPAddress
    "<COMPUTER>`n`tname: $machine`n`tMAC: $mac`n`tIP: $ip`n</COMPUTER>" | Out-File F:\scripts\wmi_mac_output.txt
}


catch [Exception]
{
    if ($_.Exception.GetType().Name -eq "COMException")
    {
       "$comp has no winrm" > f:\scripts\docs\error.txt
    }
}
}

Thank you.

Upvotes: 2

Views: 2478

Answers (1)

tby
tby

Reputation: 351

I can catch the exception, but apparently only the last one, because the output in my error file only has the name of the last computer in the list.

The issue is that the error.txt is being overwritten instead of appended.

"$comp has no winrm" > f:\scripts\docs\error.txt

Change to:

"$comp has no winrm" >> f:\scripts\docs\error.txt

Upvotes: 3

Related Questions