Get-Counter failing with error : A counter with a negative denominator value was detected
-
Wednesday, February 29, 2012 6:09 PM
Hi Folks,
I have a weird situation where I am sampling the CPU usage for small duration and taking an average of the usage using the 'Get-Counter' command. This command seems to work well when tried directly in the powershell prompt. However, when we use the same command in script, the following error throws up,
Starting process to consume CPU cycles Get-Counter : A counter with a negative denominator value was detected. At C:\Monitor.ps1:100 char:29 + $sys_cpu_obj = Get-Counter <<<< '\Processor(_Total)\% Processor Time' + CategoryInfo : InvalidResult: (:) [Get-Counter], Exception + FullyQualifiedErrorId : CounterApiError,Microsoft.PowerShell.Commands.GetCounterCommand PS C:\> Get-Counter '\Processor(_Total)\% Processor Time' Timestamp CounterSamples --------- -------------- 2/29/2012 9:56:47 AM \\vms1\processor(_total)\% processor time : 26.2817087701422 PS C:\>
Here is the routine that is being executed,
function sample-CPUUsage([int] $iterations=3,[int] $sampling_interval=2){ [long] $sum=0 # Collect an average of physical memory usage for($i=0; $i -lt $iterations; $i++){ $sys_cpu_obj = Get-Counter '\Processor(_Total)\% Processor Time' [long] $cpu_usage=$($sys_cpu_obj.CounterSamples).CookedValue $sum+=$cpu_usage Start-Sleep -Seconds $sampling_interval } [long] $sum=[long] ($sum/$iterations) return $sum }
Why am I getting this error when running the same command from the script ?
-Pranav
All Replies
-
Wednesday, February 29, 2012 6:15 PM
Your function seems to work on my machine.
Grant Ward, a.k.a. Bigteddy
-
Wednesday, February 29, 2012 7:27 PMThis error might be a bug with powershell. It doesn't always shows up. I am not sure what to do with this...
-Pranav
-
Thursday, March 01, 2012 5:36 AMModerator
Hi,
I cannot reproduce your issue either. It seems like that this issue a issue related with your environment.
Based on the error message "A counter with a negative denominator value was detected", it seems like that $iterations sometimes is treated as a negative number. How about change [long] $sum=[long] ($sum/$iterations)
as[long] $sum=[system.math]::abs([long] ($sum/$iterations))
Best Regards,
Yan Li
Yan Li
TechNet Community Support
- Marked As Answer by Yan Li_Microsoft Contingent Staff, Moderator Monday, March 05, 2012 4:51 AM

