[英]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 write-host語句,而不是IF write-host語句。 不要擔心。 我不是想作弊或任何類似的事情;)。 我簡直傻眼了,這么簡單的腳本怎么這么容易就崩潰了! 任何幫助表示贊賞!
將字符串"\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!"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.