我使用的脚本对平均CPU和内存利用率执行基本运行状况检查,并检查特定服务是否正在运行。输出将显示为HTML。如果CPU /内存利用率大于89%,或者如果服务未运行,则受影响的服务器将显示为红色。该脚本工作得很好,除了一些不一致的地方,服务器,即使在使用时,也会是红色的。
这是我正在使用的powershell脚本:
$ServerListFile = "C:\Scripts\HealthCheck\ServerList.txt"
$ServerList = Get-Content $ServerListFile -ErrorAction SilentlyContinue
$Date = Get-Date -Format M.d.yyyy
$Result = @()
foreach ($computername in $ServerList) {
$AVGProc = Get-WmiObject -ComputerName $computername Win32_Processor |
Measure-Object -Property LoadPercentage -Average |
Select-Object Average
$OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computername |
Select-Object @{Name = "MemoryUsage"; Expression = {"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }}
$Service1 = Get-Service -ComputerName $computername -Name Service1
$Service2 = Get-Service -ComputerName $computername -Name Service2
$Result += [PSCustomObject] @{
ServerName = "$computername"
CPULoad = "$($AVGProc.Average)%"
MemLoad = "$($OS.MemoryUsage)%"
Service1 = "$($Service1.Status)"
Service2 = "$($Service2.Status)"
}
$Outputreport = "<HTML><TITLE> Server Health Check </TITLE>
<BODY background-color:peachpuff>
<font color =""#99000"" face=""Microsoft Tai le"">
<H2> Server Health Check </H2></font>
<Table border=1 cellpadding=7 cellspacing=0>
<font face=""Calibri"">
<TR bgcolor=white align=center>
<TD><B> Server Name </B></TD>
<TD><B> Avrg.CPU </B></TD>
<TD><B> Memory </B></TD>
<TD><B> Service1 </B></TD>
<TD><B> Service2</B></TD></TR>"
foreach ($Entry in $Result) {
if (($Entry.MemLoad -gt "89") -Or ($Entry.CPULoad -gt "89") -or ($Entry.Service1 -eq "Stopped") -or ($Entry.Service2 -eq "Stopped")) {
$Outputreport += "<TR bgcolor=red>"
} else {
$Outputreport += "<TR bgcolor=lightgreen>"
}
$Outputreport += "<TD>$($Entry.Servername)</TD><TD align=center>$($Entry.CPULoad)</TD><TD align=center>$($Entry.MemLoad)</TD><TD align=center>$($Entry.Service1)</TD><TD align=center>$($Entry.Service2)</TD></TR>"
}
$Outputreport += "</Table></BODY></HTML>"
}
$Outputreport | Out-File C:\Scripts\HealthCheck\ServerHealthCheck\HealthCheck_$Date.htm
谢谢!
答案 0 :(得分:3)
当你真的对数字比较感兴趣时,不要使用字符串比较 - 数字串的正常性不等于它的数字对应的数字。请考虑以下比较操作:
PS C:\> 9 -gt 89
False
PS C:\> "9" -gt "89"
True
首先,更改结果对象以将百分比作为数字来代替:
$Result += [PSCustomObject] @{
ServerName = "$computername"
CPULoad = $AVGProc.Average
MemLoad = $OS.MemoryUsage
Service1 = "$($Service1.Status)"
Service2 = "$($Service2.Status)"
}
然后更改if
语句以将它们作为数字进行比较:
if (($Entry.MemLoad -gt 89) -Or ($Entry.CPULoad -gt 89) -or ($Entry.Service1 -eq "Stopped") -or ($Entry.Service2 -eq "Stopped"))
最后,在最终输出中添加%
符号:
$Outputreport += "<TD>$($Entry.Servername)</TD><TD align=center>$($Entry.CPULoad)%</TD><TD align=center>$($Entry.MemLoad)%</TD><TD align=center>$($Entry.Service1)</TD><TD align=center>$($Entry.Service2)</TD></TR>"