Author Posts

January 3, 2018 at 8:45 pm

#I am new to powershell # Trying to get memory usage information of few servers. I was able to get the result for few servers and not for few others(i get "RPC server unavailable" error) I'm guessing that's a firewall issue and i'm ok with that but i need the list of servers that the command failed to run. I tried to run below "script" with no luck.


$x = get-content .\abc.txt
foreach($a in $x)
{ $wmi = gwmi -class win32_operatingsystem -computername $a -errorvariable err } 
if ($err -gt 0)
{ write-host"$y" }

I got the information that i need by comparing the result that i have got and the original text file. But trying to know the better way to trap the error

January 3, 2018 at 8:52 pm

Try using a Try/Catch, like so:

foreach ($a in (Get-Content .\abc.txt)) {
    try {
        $WMI = Get-WmiObject -Class win32_operatingsystem -ComputerName $a -ErrorAction STOP
        }
    catch {
        Write-Host "$a failed with error: $_"
        }
    }

You can use $WMI to use that data later on, but if it fails it writes the computer name and the error to the screen. You can take Write-Host and change that to something like this to output to a log file:

"$a failed with error: $_" | Out-File $path -append

January 3, 2018 at 9:14 pm

That worked.Thank you!