为什么我的 Powershell IF...Else 循环总是执行 ELSE 语句,无论变量结果是什么?

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

我正在为我在 powershell 中的实习制作一个简单的脚本,它使用简单的东西,如变量、IF...ELSE 语句以及 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!"
}

这就是脚本。无论 CPU 利用率是多少,它总是会说 ELSE 写主机语句, 而不是 IF 写主机陈述。不要担心。我不是想作弊或任何类似的事情;)。我简直傻眼了,这么简单的脚本怎么这么容易就崩溃了!感谢您的帮助!

将字符串 "\Processor(_Total)\% Processor Time" 与数字 50 进行比较没有多大意义。

相反,使用 Where-Object 来测试 Get-Counter 返回的任何计数器样本是否超过阈值:

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