条件为 "-ge"的 PowerShell if 语句未按预期工作

标签 powershell

我有一个非常简单的 PowerShell 脚本,它使用 Select-String 从日志文件中提取特定值的最新条目,然后检查该值是否大于或等于 1000(通常该值在 0-10 之间) )。如果该值大于或等于 1000,则应使用 Send-MailMessage 发送警报。

这看起来很简单,但我无法弄清楚为什么下面的脚本在值远低于 1000 时(例如,当它等于 5 或​​ 8 时)向我发送警报:

# Log file parsing:
$Date = Get-Date -Format "yyMMdd HH:mm:ss"
$LogName = "LOG.log"
$LogFile = Join-Path -Path "C:\DIR1\DIR2\log" -ChildPath $LogName
$LastVALUE = Select-String -Path $LogFile -Pattern 'VALUE:\((\d+)\)' | ForEach-Object {$_.Matches.Groups[1].Value} | select -last 1

# Notification Settings:
$SmtpServer = "redacted.redacted.edu"
$From = "SERVER <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="413224333724330133242520223524256f242534" rel="noreferrer noopener nofollow">[email protected]</a>>"
$Recipients = "<<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="26414954425f66544342474552434208434253" rel="noreferrer noopener nofollow">[email protected]</a>>"
$Subject = "VALUE Alert"
$Body = "$Date`: Latest VALUE: $LastVALUE"

if ( $LastVALUE -ge 1000 )
{
    Send-MailMessage -SmtpServer $SmtpServer -From $From -To $Recipients -Subject $Subject -Body $Body
}

Windows 任务计划程序每 15 分钟调用一次该脚本。当值为 0(通常为 0)时,不会发送警报(如预期),但当该值大于 0 但远低于 1000 时,会发送警报。

测试时,如果我将条件更改为“-le”,我会收到准确显示值 0(或接近 0)的警报。

我已多次通读文档以确认我的语法是否正确,但似乎找不到对此行为的任何明显解释。

最佳答案

当前,您正在将字符串与整数进行比较($_.Matches.Groups[1].Value 是一个字符串)。由于字符串位于比较的左侧,因此 PowerShell 首先将右侧的整数(本例中为 1000)转换为字符串,然后使用指令进行字符串比较,请参阅 Compare stringsabout Comparison Operators

直观地说:

'5' -ge 1000 # true
5 -ge 1000   # false

解决方案非常简单,您可以将字符串强制转换为整数:

if ([int] $LastVALUE -ge 1000) {
    # do stuff
}

或者更改顺序,将整数放在左侧,以便本质上发生强制转换:

if (1000 -lt $LastVALUE) {
    # do stuff
}

关于条件为 "-ge"的 PowerShell if 语句未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77355270/

相关文章:

powershell - 将Get-WebAppPoolState返回的值分配给Powershell中的变量

powershell - 如何使用powershell仅对第二列值求和?

regex - Powershell RegEx 在字符串开头匹配负向后查找

bash - 如何在错误时停止Powershell脚本?

powershell - 如何创建一个关联数组,最好是单行?

powershell - New-SelfSignedCertificate -CertStoreLocation 找不到路径

powershell - powershell gui选择列表突出显示

powershell - Test-WSMan 使用 powershell 失败

powershell - Powershell:在AD中检查重复的电子邮件

Powershell 脚本无法写入正确的变音符号 - Powershell 本身会写入