donut_duncker
donut_duncker

Reputation: 13

powershell: cpu usage, function does not work for value 100

I am trying to provide a short script to inform me about the CPU usage over some limet but it works only if CPU < 100% but fails if it works 100% CPU

$trashhold=90 
$doit=Get-WmiObject Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select Average | Out-String

if ($doit -match "\d+"){ 
$doit = $matches[0]; 
}

if ($doit -gt $trashhold)
    {
        send email bla bla
    }
else 
    {
        Write-Output "less than $limit, do nothing"
    }

Basically regex takes number values from Get-WmiObject function and script works if cpu is 99 or less. For 100 it goes for else even it is bigger than trashhold (90). Where is the mistake?

try to catch error but withoout results (regex is returning correct numbers)

Upvotes: 1

Views: 115

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60045

There is no need for Out-String and no need for either, you're just overcomplicating it:

$threshold = 90
$cpuUsage  = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average 

if($cpuUsage -gt $threshold) {
    # send email blah blah with `$cpuUsage`
}
else {
    "Less than $threshold, do nothing"
}

What you're looking to do is to obtain the Property Value from the LoadPercentage Property, this can be done either via member-access enumeration (as shown in this answer) or using Select-Object -ExpandProperty LoadPercentage. ForEach-Object LoadPercentage would also work (see -MemberName parameter for more info). There are other methods too, though these are the most common ones.

Upvotes: 2

Related Questions