如果我的 SQL mdf 数据文件的剩余可用空间小于 2000 MB,我尝试设置警报。见下文:
\n\n$SQLInstances = "A","B","C"\n\n$SQLQuery = " USE DB\n SELECT CONVERT(DECIMAL(10, 2), CAST(CAST(10240 - size/128.0 AS NVARCHAR(50)) + size/128.0 - CAST(FILEPROPERTY(name, \'SpaceUsed\') AS INT)/128.0 AS NVARCHAR(50))) AS ActualSpaceAvailableMB\n FROM sys.database_files\n WHERE name = \'DB\'"\n\n$login = "XYZ"\n$password = "123" | Convertto-SecureString -AsPlainText -Force\n$creds = New-Object System.Management.Automation.Pscredential -Argumentlist $login,$password\n$SMTPServer = "10.0.0.0.0.0" # This is your SMTP Server \n$to = "ME@ME.COM"# This is the recipient smtp address 1\n$from = "NOREPLY@YOU.COM" # This will be the sender\xc3\x82\xc2\xb4s address \n\nforeach ($SQLInstance in $SQLInstances) {\n $output = Invoke-Sqlcmd -ServerInstance $SQLInstance -Database DB -Query $SQLQuery |\n Select-Object -ExpandProperty ActualSpaceAvailableMB #-QueryTimeout 1200 -Verbose -ErrorAction Stop 4>&1 \n\n if ($output -lt 2000 ) {\n Send-MailMessage -SmtpServer $SMTPServer -Credential $creds -To $to -From $from -Subject " Alert at $SQLInstance" -Body "free space is $output MB. Please investigate!!"\n } else {\n Write-Output "Actual size is not less than 2 GB"\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n现在的问题是,有时警报会给出不正确的结果,即即使$output变量中的值大于 2000 MB,电子邮件仍在发送。$output我希望它仅在值小于 2000 时发送电子邮件。有什么想法吗?
PowerShell 中的比较往往会产生意外结果,因为 PowerShell 尝试调整第二个操作数的类型以匹配第一个操作数的类型。因此,如果您的第一个操作数是字符串,则比较将是字符串比较,而不是数字比较。
示范:
PS C:\> $s = '20' PS C:\> $s -gt 10 # ⇔ "20" -gt "10" 真的 PS C:\> $s -gt 100 # ⇔ "20" -gt "100" 真的 PS C:\> $s -gt 3 # ⇔ "20" -gt "3" 错误的
为了缓解这种情况,将第一个操作数转换为数字类型:
PS C:\> [int]$s -gt 100 错误的 PS C:\> [int]$s -gt 3 真的
| 归档时间: |
|
| 查看次数: |
2793 次 |
| 最近记录: |