'Why does my Powershell IF...Else loop always do the ELSE statement, no matter what the variable result is?

I am making a simple script for my internship in powershell, that uses simple stuff like variables, the IF...ELSE statement, as well as Get-Counter.

$CpuLoad = "\Processor(_Total)\% Processor Time"
$Threshold = 50
Get-Counter -Counter $CpuLoad -SampleInterval 1 -MaxSamples 10
IF($CpuLoad -gt $Threshold) {
Write-Host "CPU Utilizacija ir lielaka par 50 procentiem!"
} Else {
Write-Host "Viss ok!"
}

That is the script. No matter what the CPU utilization percentage is, it will always say the ELSE write-host statement, not the IF write-host statement. Do not worry. I am not trying to cheat or anything of the sort ;). I'm simply dumb-founded as to how such a simple script can break so easily! Any help is appreciated!



Solution 1:[1]

Comparing the string "\Processor(_Total)\% Processor Time" to the number 50 doesn't make much sense.

Instead, use Where-Object to test if any of the counter samples returned by Get-Counter exceeds the threshold:

$CpuLoad = "\Processor(_Total)\% Processor Time"
$Threshold = 50
$samplesExceedingThreshold = Get-Counter -Counter $CpuLoad -SampleInterval 1 -MaxSamples 10 |ForEach-Object CounterSamples |Where-Object CookedValue -gt $threshold |Select-Object -First 1

if($samplesExcheedingThreshold){
    Write-Host "CPU Utilizacija ir lielaka par 50 procentiem!"
} else {
    Write-Host "Viss ok!"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mathias R. Jessen