I have a very simple piece of code, It has to be simple as I am a beginner. I am trying to catch some errors coming out of Get-WmiObject. The idea being, that if I receive an error (presumably the $machine is not accessible) I wish to put the $machine in an array and print at the end,
So… what’s the problem?
Although there are errors based on masculine in the text file, those machines are unreachable, still as I debug, the errors are not caught.
I’m not sure what “masculine “ means here, but the problem is you haven’t enabled error trapping. I suggest reading “the big book of PowerShell error handling,” which is free on our ebooks page.
You can only catch terminating errors. Try setting “-ErrorAction” to Stop
Try { $hrdsvrs = Get-WmiObject -class Win32_processor -computername $macine -ErrorAction Stop | ft systemname,Name,DeviceID,NumberOfCores,NumberOfLogicalProcessor; } Catch { $errs.add($macine) } # Write-Output $hrdsvrs;
Notice the difference in output between these two commands
@('Realcomputer1','fakecomputer','Realcomputer1') | %{try{Get-WmiObject -Class Win32_OperatingSystem -ComputerName $PSItem}catch{'Something Happened'}}
vs.
@('Realcomputer1','fakecomputer','Realcomputer1') | %{try{Get-WmiObject -Class Win32_OperatingSystem -ComputerName $PSItem -ErrorAction Stop}catch{'Something Happened'}}
I HATE SPELL CHECKER! yeah, that was supposed to say machines.
forgive my typo!! (typed the same hostname twice in my example)
@('Realcomputer','fakecomputer','Realcomputer1') | %{try{Get-WmiObject -Class Win32_OperatingSystem -ComputerName $PSItem}catch{'Something Happened'}}
vs.
@('Realcomputer','fakecomputer','Realcomputer1') | %{try{Get-WmiObject -Class Win32_OperatingSystem -ComputerName $PSItem -ErrorAction Stop}catch{'Something Happened'}}
Try I this way…
Clear-Host $errs.ForEach{$errs.Clear()} $Servers = "$env:COMPUTERNAME",'Lab01','localhost','Lab02','127.0.0.1' $errs = $null $errs = @{} foreach($machine in $Servers) { Try { Get-WmiObject -class Win32_processor -computername $machine -ErrorAction Stop | ft systemname,Name,DeviceID,NumberOfCores,NumberOfLogicalProcessor } Catch { $errs.add("$machine",'Connection Failed') } } if ($errs.Count -gt 0) { Write-Warning -Message 'ERRORS' $errs }
LOL SilentlyContinue means “do not trap errors.” Use Stop. And please, read the very concise ebook I referenced above. It would have made all that easier for you! That’s why Dave wrote it!
Hey DonJ, I get that (I have read every book you have on this site - and regular recommend them to other - and more of course), and that is what I had, but I posted a previous version. It was late when I did this and I’m very old, so, half-timers kicks in and stuff happens. So, corrected.