简体   繁体   中英

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!

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!"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM