如何使用if条件在PowerShell脚本中更改HTML表格中的单元格颜色

时间:2018-03-14 14:04:18

标签: html powershell

我在下面的脚本中计算了我们环境中快照的年龄(准确地说早于一天的快照)。我的代码和当前输出如下:

Add-PSsnapin VMware.VimAutomation.Core

# HTML formatting
$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: LightBlue}"
$a = $a + "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: white}"
$a = $a + "</style>"

Connect-VIServer -Server ******-User *****-Password *****

# Main section of check
Write-Host "Checking VMs for for snapshots"
$date = Get-Date
$datefile = Get-Date -UFormat '%m-%d-%Y-%H%M%S'


$filename = "C:\Temp\snaps_older_than_3\" + $datefile + ".htm"
$ss = Get-VM |
      Get-Snapshot |
      Where {$_.Created -lt (Get-Date).AddDays(-1)} |
      Select-Object vm, name, SizeGB, SizeMB, Created, powerstate,
          @{Name='Age';Expression={(New-TimeSpan -Start $_.Created -End $date).Days}} |
      ConvertTo-Html -Head $a -Body "<H2>VM Snapshot Report </H2>" |
      Out-File $filename

Write-Host " Complete " -ForegroundColor Green
Write-Host "Your snapshot report has been saved to:" $filename

$SMTPServer = "******"
$SMTPPort = 25
$username = "******"

#Define the receiver of the report
$to = "******"
$subject = "VM Snapshot Report"
$body = "VM Snapshot Report"
$attachment = New-Object Net.Mail.Attachment($filename)
$message = New-Object System.Net.Mail.MailMessage
$message.Subject = $subject
$message.Body = $body
$message.To.Add($to)
$message.From = $username
$message.Attachments.Add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $false
#$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.Send($message)

Write-Host "Mail Sent"

enter image description here

我想要做的是,在下面的代码中,我想根据年龄值确定我的年龄细胞的颜色。例如,如果年龄小于3,我希望该单元格为绿色,如果是3则应为蓝色,如果它穿过则应为红色。

$ss = Get-VM |
      Get-Snapshot |
      Where {$_.Created -lt (Get-Date).AddDays(-1)} |
      Select-Object vm, name, SizeGB, SizeMB, Created, powerstate,
          @{Name='Age';Expression={(New-TimeSpan -Start $_.Created -End $date).Days}} |
      ConvertTo-Html -Head $a -Body "<H2>VM Snapshot Report </H2>" |
      Out-File $filename

我搜索了很多内容并在某人的代码下面找到了代码,但我真的无法做到这一点。

$servers = "mccoyb02", "foo", "mccoyb01", "reisrv1"
$path = "c:\ephemeral\uptime.html"

$header = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>System Status Report</title>
<style type="text/css">
<!--
body {
background-color: #E0E0E0;
font-family: sans-serif
}
table, th, td {
background-color: white;
border-collapse:collapse;
border: 1px solid black;
padding: 5px
}
-->
</style>
"@
$body = @"
<h1>Server Status</h1>
<p>The following report was run on $(get-date).</p>
"@

$results = foreach ($server in $servers) {
    if (Test-Connection $server -Count 1 -EA 0 -Quiet) {
        $status = "Up"
    } else {
        $status = "Down"
    }
    [PSCustomObject]@{
        ServerName = $server
        Reuslts = $status
    }
}

$results | ConvertTo-Html -Head $header -Body $body | foreach {
    $PSItem -replace "<td>Down</td>", "<td style='background-color:#FF8080'>Down</td>"
} | Out-File C:\Ephemeral\uptime.html
& .\uptime.html

输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

来自杰弗里希克斯(https://www.youtube.com/watch?v=QdK3qM5jnYw)的视频向我指出了正确的方向。 Petri上的文章得到了样式单元格(而不仅仅是行)的解决方案。我建议你也观看/阅读这些内容。

我还将$head变量编辑为Here-String,以便于阅读和编辑。

单元格的样式要求它首先将对象转换为XML对象(请注意-Fragment开关!)。然后可以解析,编辑此XML对象,最后将其转换为HTML。希望评论清楚。

Add-PSsnapin VMware.VimAutomation.Core

# HTML formatting
$head = @"
<style>
BODY{background-color:white;}
TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: LightBlue}
TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: white}
.green{background-color:#d5f2d5}
.blue{background-color:#e0eaf1}
.red{background-color:#ffd7de}
</style>
"@

Connect-VIServer -Server ****** -User ***** -Password *****

# Main section of check
Write-Host "Checking VMs for for snapshots"
$date = Get-Date
$datefile = Get-Date -UFormat '%m-%d-%Y-%H%M%S'

$filename = "C:\Temp\snaps_older_than_3\" + $datefile + ".htm"

# Convert the selection to an XML object
[xml]$xmlObject = Get-VM |
      Get-Snapshot |
      Where {$_.Created -lt (Get-Date).AddDays(-1)} |
      Select-Object vm, name, SizeGB, SizeMB, Created, powerstate,
          @{Name='Age';Expression={(New-TimeSpan -Start $_.Created -End $date).Days}} |
      ConvertTo-Html -Fragment

# Parse XML object and set colour class according to value in last column ("Age")
for($i=1;$i -le $xmlObject.table.tr.count-1;$i++) {
    if(($xmlObject.table.tr[$i].td[-1] -as [int]) -lt 3) {
        $xmlObject.table.tr[$i].ChildNodes[($xmlObject.table.tr[$i].ChildNodes.Count-1)].SetAttribute('class','green')
    } elseif (($xmlObject.table.tr[$i].td[-1] -as [int]) -eq 3) {
        $xmlObject.table.tr[$i].ChildNodes[($xmlObject.table.tr[$i].ChildNodes.Count-1)].SetAttribute('class','blue')
    } else {
        $xmlObject.table.tr[$i].ChildNodes[($xmlObject.table.tr[$i].ChildNodes.Count-1)].SetAttribute('class','red')
    }
}

# Define body and append the modified XML object
$body = @"
<H2>VM Snapshot Report </H2>
$($xmlObject.innerxml)
"@

# Convert to HTML and save the file
ConvertTo-Html -Head $head -Body $body |
      Out-File $filename

Write-Host " Complete " -ForegroundColor Green
Write-Host "Your snapshot report has been saved to:" $filename

$SMTPServer = "******"
$SMTPPort = 25
$username = "******"

#Define the receiver of the report
$to = "******"
$subject = "VM Snapshot Report"
$body = "VM Snapshot Report"
$attachment = New-Object Net.Mail.Attachment($filename)
$message = New-Object System.Net.Mail.MailMessage
$message.Subject = $subject
$message.Body = $body
$message.To.Add($to)
$message.From = $username
$message.Attachments.Add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $false
#$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.Send($message)

Write-Host "Mail Sent"