简体   繁体   English

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

[英]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.我正在为我在 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!"
}

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.不管CPU利用率是多少,它总是说ELSE write-host语句,而不是IF write-host语句。 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.将字符串"\Processor(_Total)\% Processor Time"与数字50进行比较没有多大意义。

Instead, use Where-Object to test if any of the counter samples returned by Get-Counter exceeds the threshold:相反,使用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!"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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