英文:
Powershell dynamic HTML table
问题
if ($column -eq 'Last Result' -and $val -match '^\d+$') {
# 特殊情况,如果列是 'Last Result' 且 $val 是全数字,且 $val 等于 0,使用背景颜色绿色,否则为红色
$resultColor = if ([int]$val -eq 0) { '#92D050' } else { '#FF4606' }
$td = '<td style="background-color: {0}; text-align: right;">{1}</td>' -f $resultColor, $val
}
elseif ($column -eq 'Last Result1' -and $val -match '^\d+$') {
# 特殊情况,如果列是 'Last Result1' 且 $val 是全数字,且 $val 等于 0,使用背景颜色绿色,否则为红色
$resultColor = if ([int]$val -eq 0) { '#92D050' } else { '#FF4606' }
$td = '<td style="background-color: {0}; text-align: right;">{1}</td>' -f $resultColor, $val
}
英文:
I have the following (partial) script which gets the content of a AD Replication status and formats it as a table, then sends it in an email.
My question is : I want to create a dynamic HTML table like my desired output. how can we do that?
if Last Result is equal 0 I want that cell to be colored in green, if it is greater than 0 should be in red.
My desired output :
Here is my script :
$style = @"
<style>
body, table {font-family: sans-serif; font-size: 11pt; color: #1F497D;}
table {border: 1px solid black; border-collapse: collapse; color: #000000;}
th {border: 1px solid black; background: #dddddd; padding: 3px;}
td {border: 1px solid black; padding: 3px;}
</style>
"@
$mailTemplate = @"
<html><head>{0}</head><body>
This an automated message.<br />
{1}
Please review the attachment.<br /><br />Thank you.
</body></html>
"@
$DCs = Get-ADDomainController -Filter * |sort name
$results = @()
ForEach ($DC in $DCs) {
$ReplStatuses = Get-ADReplicationPartnerMetadata -target $DC.HostName -PartnerType Both -ErrorAction SilentlyContinue
If ($ReplStatuses) {
ForEach ($ReplStatus in $ReplStatuses) {
$Partner = $ReplStatus.Partner.Split(",")[1].Replace("CN=","")
$results += [pscustomobject] @{
'Source DC' = $DC.HostName.ToUpper()
'Partner DC' = (Get-ADComputer $Partner).DNSHostName.ToUpper()
Direction = $ReplStatus.PartnerType
Type = $ReplStatus.IntersiteTransportType
'Last Attempt' = $ReplStatus.LastReplicationAttempt
'Last Success' = $ReplStatus.LastReplicationSuccess
'Last Result' = $ReplStatus.LastReplicationResult
}
}
} Else {
$results += [pscustomobject] @{
'Source DC' = $DC.HostName.ToUpper()
'Partner DC' = "N/A"
Direction = "N/A"
Type = "N/A"
'Last Attempt' = "N/A"
'Last Success' = "N/A"
'Last Result' = "N/A"
}
}
}
$table = ($results | ConvertTo-Html -As Table -Fragment) -join [environment]::NewLine
$mailParams = @{
To = 'user@contoso.com'
From = 'user@contoso.com'
Subject = 'AD Status'
Body = $mailTemplate -f $style , $table
BodyAsHtml = $true
Priority = 'High'
SmtpServer = ''
Encoding = 'UTF8'
}
Send-MailMessage @mailParams
EDIT1:
if ($column -eq 'Last Result' -and $val -match '^\d+$') {
# special case, if column is 'Last Result' and $val is all numeric
# and $val equals 0, use backcolor green else red
$resultColor = if ([int]$val -eq 0) { '#92D050' } else { '#FF4606' }
$td = '<td style="background-color: {0}; text-align: right;">{1}</td>' -f $resultColor, $val
}
elseif $column -eq 'Last Result1' -and $val -match '^\d+$') {
# special case, if column is 'Last Result1' and $val is all numeric
# and $val equals 0, use backcolor green else red
$resultColor = if ([int]$val -eq 0) { '#92D050' } else { '#FF4606' }
$td = '<td style="background-color: {0}; text-align: right;">{1}</td>' -f $resultColor, $val
}
答案1
得分: 0
我猜我会使用自定义函数将数据转换为HTML表格。
我尝试模仿您示例图像中的样式,并对您的代码进行了一些小调整。
# 自定义函数以将数据转换为HTML表格
function ConvertTo-HTMLTable {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
$InputObject,
[string]$BackColorHeader = '#000000',
[string]$BackColorOddRow = '#305496'
)
# 接受 System.Data.DataTable 对象或 PSObject 数组并将其转换为带样式的HTML表格
# 添加类型以将HTML特殊字符替换为实体
Add-Type -AssemblyName System.Web
$sb = New-Object -TypeName System.Text.StringBuilder
[void]$sb.AppendLine('<table>')
if ($null -ne $InputObject) {
if (([object]$InputObject).GetType().FullName -eq 'System.Data.DataTable'){
# 它是一个 DataTable;将其转换为 PSObject 数组
$InputObject = $InputObject | Select-Object * -ExcludeProperty ItemArray, Table, RowError, RowState, HasErrors
}
$headers = $InputObject[0].PSObject.Properties | Select -ExpandProperty Name
[void]$sb.AppendLine('<thead><tr>')
foreach ($column in $headers) {
[void]$sb.AppendLine(("<th>{0}</th>" -f [System.Web.HttpUtility]::HtmlEncode($column)))
}
[void]$sb.AppendLine('</tr></thead><tbody>')
$row = 0
$InputObject | ForEach-Object {
# 添加斑马纹颜色行的内联样式
if ($row++ -band 1) {
$tr = "<tr style='background-color: {0};'>" -f $BackColorOddRow
}
else {
$tr = "<tr>"
}
[void]$sb.AppendLine($tr)
foreach ($column in $headers) {
[string]$val = $($_.$column)
if ($column -eq 'Last Result' -and $val -match '^\d+$') {
# 特殊情况,如果列是'Last Result'并且$val全为数字
# 如果$val等于0,使用背景颜色绿色,否则红色
$resultColor = if ([int]$val -eq 0) { '#92D050' } else { '#FF4606' }
$td = ("<td style='background-color: {0}; text-align: right;'>{1}</td>" -f $resultColor, $val)
}
else {
if ([string]::IsNullOrWhiteSpace($val)) {
$td = "<td> </td>"
}
else {
$td = "<td>{0}</td>" -f [System.Web.HttpUtility]::HtmlEncode($val)
}
}
[void]$sb.Append($td)
}
[void]$sb.AppendLine('</tr>')
}
[void]$sb.AppendLine('</tbody>')
}
[void]$sb.AppendLine('</table>')
return $sb.ToString()
}
$style = @"
<style>
body, table {font-family: sans-serif; font-size: 11pt; color: #000000;}
table {border: 1px solid black; border-collapse: collapse; color: #ffffff;}
tr {background-color: #4472C4;}
th {border: 1px solid black; background-color: #000000; padding: 3px; font-weight:normal; text-align: left;}
td {border: 1px solid black; padding: 3px;}
</style>
"@
$mailTemplate = @"
<html><head>
{0}
</head><body>
This an automated message.<br /><br />
{1}
<br />
Please review the attachment.<br /><br />Thank you.
</body></html>
"@
$DCs = Get-ADDomainController -Filter * | Sort-Object name
$results = foreach ($DC in $DCs) {
$ReplStatuses = Get-ADReplicationPartnerMetadata -target $DC.HostName -PartnerType Both -ErrorAction SilentlyContinue
If ($ReplStatuses) {
foreach ($ReplStatus in $ReplStatuses) {
$Partner = $ReplStatus.Partner.Split(",")[1].Replace("CN=","")
# 仅输出对象;它将在变量 $results 中收集
[PsCustomObject] @{
'Source DC' = $DC.HostName.ToUpper()
'Partner DC' = (Get-ADComputer $Partner).DNSHostName.ToUpper()
'Direction' = $ReplStatus.PartnerType
'Type' = $ReplStatus.IntersiteTransportType
'Last Attempt' = $ReplStatus.LastReplicationAttempt
'Last Success' = $ReplStatus.LastReplicationSuccess
'Last Result' = $ReplStatus.LastReplicationResult
}
}
}
else {
[PsCustomObject] @{
'Source DC' = $DC.HostName.ToUpper()
'Partner DC' = "N/A"
'Direction' = "N/A"
'Type' = "N/A"
'Last Attempt' = "N/A"
'Last Success' = "N/A"
'Last Result' = "N/A"
}
}
}
# 使用我们自己的函数来自定义格式化HTML表格
$table = ConvertTo-HTMLTable -InputObject $results -BackColorHeader '#000000' -BackColorOddRow '#305496'
$mailParams = @{
To = 'user@contoso.com'
From = 'user@contoso.com'
Subject = 'AD Status'
Body = $mailTemplate -f $style , $table
BodyAsHtml = $true
Priority = 'High'
SmtpServer = 'smtp.contoso.com'
Encoding = 'UTF8'
}
Send-MailMessage @mailParams
使用虚假数据,表格应如下所示:
英文:
I guess I would use my own custom function to convert the data in $results to HTML table.
I have tried to mimic the style in your example image and made some small adjustments to your code
# a custom function to convert the data to HTML table
function ConvertTo-HTMLTable {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
$InputObject,
[string]$BackColorHeader = '#000000',
[string]$BackColorOddRow = '#305496'
)
# Accepts a System.Data.DataTable object or an array of PSObjects and converts to styled HTML table
# add type needed to replace HTML special characters into entities
Add-Type -AssemblyName System.Web
$sb = New-Object -TypeName System.Text.StringBuilder
[void]$sb.AppendLine('<table>')
if ($null -ne $InputObject) {
if (([object]$InputObject).GetType().FullName -eq 'System.Data.DataTable'){
# it is a DataTable; convert to array of PSObjects
$InputObject = $InputObject | Select-Object * -ExcludeProperty ItemArray, Table, RowError, RowState, HasErrors
}
$headers = $InputObject[0].PSObject.Properties | Select -ExpandProperty Name
[void]$sb.AppendLine('<thead><tr>')
foreach ($column in $headers) {
[void]$sb.AppendLine(('<th>{0}</th>' -f [System.Web.HttpUtility]::HtmlEncode($column)))
}
[void]$sb.AppendLine('</tr></thead><tbody>')
$row = 0
$InputObject | ForEach-Object {
# add inline style for zebra color rows
if ($row++ -band 1) {
$tr = '<tr style="background-color: {0};">' -f $BackColorOddRow
}
else {
$tr = '<tr>'
}
[void]$sb.AppendLine($tr)
foreach ($column in $headers) {
[string]$val = $($_.$column)
if ($column -eq 'Last Result' -and $val -match '^\d+$') {
# special case, if column is 'Last Result' and $val is all numeric
# and $val equals 0, use backcolor green else red
$resultColor = if ([int]$val -eq 0) { '#92D050' } else { '#FF4606' }
$td = '<td style="background-color: {0}; text-align: right;">{1}</td>' -f $resultColor, $val
}
else {
if ([string]::IsNullOrWhiteSpace($val)) {
$td = '<td>&nbsp;</td>'
}
else {
$td = '<td>{0}</td>' -f [System.Web.HttpUtility]::HtmlEncode($val)
}
}
[void]$sb.Append($td)
}
[void]$sb.AppendLine('</tr>')
}
[void]$sb.AppendLine('</tbody>')
}
[void]$sb.AppendLine('</table>')
return $sb.ToString()
}
$style = @"
<style>
body, table {font-family: sans-serif; font-size: 11pt; color: #000000;}
table {border: 1px solid black; border-collapse: collapse; color: #ffffff;}
tr {background-color: #4472C4;}
th {border: 1px solid black; background-color: #000000; padding: 3px; font-weight:normal; text-align: left;}
td {border: 1px solid black; padding: 3px;}
</style>
"@
$mailTemplate = @"
<html><head>
{0}
</head><body>
This an automated message.<br /><br />
{1}
<br />
Please review the attachment.<br /><br />Thank you.
</body></html>
"@
$DCs = Get-ADDomainController -Filter * | Sort-Object name
$results = foreach ($DC in $DCs) {
$ReplStatuses = Get-ADReplicationPartnerMetadata -target $DC.HostName -PartnerType Both -ErrorAction SilentlyContinue
If ($ReplStatuses) {
foreach ($ReplStatus in $ReplStatuses) {
$Partner = $ReplStatus.Partner.Split(",")[1].Replace("CN=","")
# just output the object; it will be collected in variable $results
[PsCustomObject] @{
'Source DC' = $DC.HostName.ToUpper()
'Partner DC' = (Get-ADComputer $Partner).DNSHostName.ToUpper()
'Direction' = $ReplStatus.PartnerType
'Type' = $ReplStatus.IntersiteTransportType
'Last Attempt' = $ReplStatus.LastReplicationAttempt
'Last Success' = $ReplStatus.LastReplicationSuccess
'Last Result' = $ReplStatus.LastReplicationResult
}
}
}
else {
[PsCustomObject] @{
'Source DC' = $DC.HostName.ToUpper()
'Partner DC' = "N/A"
'Direction' = "N/A"
'Type' = "N/A"
'Last Attempt' = "N/A"
'Last Success' = "N/A"
'Last Result' = "N/A"
}
}
}
# use our own function to custom format the HTML table
$table = ConvertTo-HTMLTable -InputObject $results -BackColorHeader '#000000' -BackColorOddRow '#305496'
$mailParams = @{
To = 'user@contoso.com'
From = 'user@contoso.com'
Subject = 'AD Status'
Body = $mailTemplate -f $style , $table
BodyAsHtml = $true
Priority = 'High'
SmtpServer = 'smtp.contoso.com'
Encoding = 'UTF8'
}
Send-MailMessage @mailParams
Using fake data, the table should look like this:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论