Powershell try catch

Soldato
Joined
8 Mar 2005
Posts
3,934
Location
London, UK
So, the following code isn't doing what I think it should when failing. Infact as far as I can tell it it doesn't see a failure.
Code:
Try { $CpuUsage=(get-counter -ComputerName $hostname -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 5 -ErrorAction Stop | select -ExpandProperty countersamples | select -ExpandProperty cookedvalue | Measure-Object -Average).average

        $CpuUsage = "{0:N1}" -f $CpuUsage; return $CpuUsage
    } Catch { "Error returned while checking the CPU usage. Perfmon Counters may be at fault." }
In this example, it will attempt to get an average of CPU based on 5 samples from a host. Occasionally, the host may be up(pingable) but it is in a state where you can neither connect via RDP or interact with WMI. I suspect the try doesn't see the get-counter attempt as a failure and it simply waits indefinitely for the 5 samples to be collected.

Any ideas?
Cheers, Paul.
 
Hmmm, Thanks for giving it a go. However, exactly the same behaviour; it just sits there indefinitely. As I say the server is pingable but seemingly not allowing certain calls to it (I cannot RDP or pull up a remote tasklist) but I can browse to it, connect to its services etc.
 
So, a little further along now. The server is basically pegged at 100% CPU. Although you can browse and interact in various ways; any attempt to connect to WMI counters or directly attempting to RDP fails. So I think my original assumption holds true that the command executes successfully. it just never completes.

I've managed to get around the issue by placing this and other similar code inside another function which does successfully process based on another condition.
 
Back
Top Bottom