I'm no expert in PS but I have found it very useful as glue logic to automate little things here and there. Recently, someone asked me if there was an easy way to poll multiple servers in a load balanced environment and aggregate to results of a particular
counter on each server.
This is roughly what I came up with. It will poll all the servers and report a summation of a particular performance counter's value every 60 seconds:
while ($True) { $totalMonitorCount = 0; try { $server01CounterData = get-counter -errorAction "Stop" -counter "CounterName" -computername "Sever01NetworkName"; $server01MonitorCount = [Double]$server01CounterData.countersamples[0].cookedvalue; $totalMonitorCount += $server01MonitorCount; } catch { write-host "Something went wrong on the server. Restart the script because get-counter will never work again until you do."; $server01MonitorCount = "unknown"; } #Repeat above try/catch process for N servers, aggregating counts as we go... write-host "Total: $totalMonitorCount"; start-sleep 60; }
...This works just fine as long as there are no exceptions generated by the call to get-counter (as might happen in the case of someone restarting a service on the server), but the first time an exception happens, that exception will be reported by all subsequent
calls to get-counter even if the service is back up and running. If you restart the script, calls to get-counter begin to work again.
I suspect this is just some problem related to me not understanding how PS error handling works. Any thoughts?
What I'd like is for my script to report the errors while the server is in a bad state and then get back to working normally once the server recovers.