我创建了一个脚本来提取内存和CPU的资源使用情况,并突出显示阈值超过75%的CPU和内存较高的值。但是,我无法在 HTML 正文中嵌入的值后面附加“%”字符串
我在下面的代码中尝试了不同的方法,将 forloop 条件从 int 更改为字符串,以突出显示阈值超过 75% 的值并附加“%”字符串。但是在 HTML 正文中更改为字符串类型不会突出显示正确的值,即也不会突出显示低于 75% 的值。下面是代码片段。
$cpu_total = 0.0
$mem_total = 0.0
$thresholdPercent = "75.00%"
$header = "<style>BODY{font-family: Arial; font-size: 10pt;}"
$header = $header + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$header = $header + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$header = $header + "TD{border: 1px solid black; padding: 5px; }"
$header = $header + ".critical{background-color:yellow}"
$header = $header + ".normal{background-color:white}"
$header = $header + "</style>"
foreach ($cpuData in $CPUMetricData.Data.Average) {
$cpu_total += $cpuData / 14
}
foreach ($memData in $memMetricData.Data.Average) {
$mem_total += $memData / 14
$totalMemInGB = [math]::floor($virtualMachineMem / 1000)
$availableMemInGB = [math]::round($mem_total / 1000 / 1000 / 1000, 2)
$memUsagePercent = [math]::round(($totalMemInGB - $availableMemInGB) / $totalMemInGB * 100, 2)
}
[PSCustomObject]@{
vmName = $virtualMachineName
resourceGroupName = $resourceGroupName
vmSize = $virtualMachineSize
PrivateIP = $privateIpAddress
CpuCores = $virtualMachineCpu
MemoryInGB = [string]::Concat($totalMemInGB, "GB")
CpuUsagePercent = [string]::Concat([math]::round($cpu_total, 2), "%")
# MemoryUsagePercent = $memUsagePercent
MemoryUsagePercent = [string]::Concat($memUsagePercent, "%")
}
}
[xml]$HTMLBody = $VMResourceInfo `
| Select-Object vmName, resourceGroupName, vmSize, PrivateIP, CpuCores, MemoryInGB, CpuUsagePercent, MemoryUsagePercent `
| ConvertTo-Html -Fragment `
for ($i = 1; $i -le $HTMLBody.table.tr.count - 1; $i++) {
if (($HTMLBody.table.tr[$i].td[-1] -as [string]) -gt $thresholdPercent) {
$HTMLBody.table.tr[$i].ChildNodes[($HTMLBody.table.tr[$i].ChildNodes.Count - 1)].SetAttribute('class', 'critical')
}
else {
$HTMLBody.table.tr[$i].ChildNodes[($HTMLBody.table.tr[$i].ChildNodes.Count - 1)].SetAttribute('class', 'normal')
}
}
$body = "<h1>Server Status</h1>"
$body = $body + "<p>Below is the weekly usage report for Azure VMs from $st to $et.</p>"
$body = $body + $($HTMLBody.innerxml)
$convertToHtmlBody = ConvertTo-Html -Head $header -Body $body | Out-String
事实上,
-gt
通常仅在(至少)LHS是实际的数字时才执行数字比较,根据定义,不是XML文档的文本节点值的情况。
但是,如果确保两个字符串操作数的格式相同,位数和小数位数完全相同(
.
和 %
等静态部分相同),则生成的 lexical 比较相当于数值比较。
鉴于
$thresholdPercent
的逐字值是 75.00%
,您可以使用以下技术将表格值设置为相同的格式:
# The raw numerical calculation to calculate the ratio:
# No need to calculate a *percentage* here, and no need to *round*.
$memUsagePercent = ($totalMemInGB - $availableMemInGB) / $totalMemInGB
# ...
[PSCustomObject] @{
# ...
# Now convert the ratio to a string representation along the lines of
# '75.00%' or '09.00%' percent:
MemoryUsagePercent = $memUsagePercent.ToString('P2').PadLeft(6, '0')
}