Powershell 动态 HTML 表格

huangapple go评论78阅读模式
英文:

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 :

Powershell 动态 HTML 表格

Here is my script :

$style = @&quot;
&lt;style&gt;
    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;}
&lt;/style&gt;
&quot;@

$mailTemplate = @&quot;
&lt;html&gt;&lt;head&gt;{0}&lt;/head&gt;&lt;body&gt;
This an automated message.&lt;br /&gt;
{1}
Please review the attachment.&lt;br /&gt;&lt;br /&gt;Thank you.
&lt;/body&gt;&lt;/html&gt;
&quot;@

$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(&quot;,&quot;)[1].Replace(&quot;CN=&quot;,&quot;&quot;)

            $results += [pscustomobject] @{
                &#39;Source DC&#39; = $DC.HostName.ToUpper()
                &#39;Partner DC&#39; = (Get-ADComputer $Partner).DNSHostName.ToUpper()
                Direction = $ReplStatus.PartnerType
                Type = $ReplStatus.IntersiteTransportType
                &#39;Last Attempt&#39; = $ReplStatus.LastReplicationAttempt
                &#39;Last Success&#39; = $ReplStatus.LastReplicationSuccess
                &#39;Last Result&#39; = $ReplStatus.LastReplicationResult
                }
        }
    } Else {
       
        $results += [pscustomobject] @{
            &#39;Source DC&#39; = $DC.HostName.ToUpper()
            &#39;Partner DC&#39; = &quot;N/A&quot;
            Direction = &quot;N/A&quot;
            Type = &quot;N/A&quot;
            &#39;Last Attempt&#39; = &quot;N/A&quot;
            &#39;Last Success&#39; = &quot;N/A&quot;
            &#39;Last Result&#39; = &quot;N/A&quot;
            }
    }
}

$table = ($results | ConvertTo-Html -As Table -Fragment) -join [environment]::NewLine


    
    $mailParams = @{
        To         = &#39;user@contoso.com&#39;
        From       = &#39;user@contoso.com&#39;
        Subject    = &#39;AD Status&#39;
        Body       = $mailTemplate -f $style , $table
        BodyAsHtml = $true
        Priority   = &#39;High&#39;
        SmtpServer = &#39;&#39;
        
        Encoding   = &#39;UTF8&#39;
       
    }
    Send-MailMessage @mailParams

EDIT1:

if ($column -eq &#39;Last Result&#39; -and $val -match &#39;^\d+$&#39;) {
				# special case, if column is &#39;Last Result&#39; and $val is all numeric
				# and $val equals 0, use backcolor green else red
				$resultColor = if ([int]$val -eq 0) { &#39;#92D050&#39; } else { &#39;#FF4606&#39; }
				$td = &#39;&lt;td style=&quot;background-color: {0}; text-align: right;&quot;&gt;{1}&lt;/td&gt;&#39; -f $resultColor, $val
			}
			
elseif $column -eq &#39;Last Result1&#39; -and $val -match &#39;^\d+$&#39;) {
				# special case, if column is &#39;Last Result1&#39; and $val is all numeric
				# and $val equals 0, use backcolor green else red
				$resultColor = if ([int]$val -eq 0) { &#39;#92D050&#39; } else { &#39;#FF4606&#39; }
				$td = &#39;&lt;td style=&quot;background-color: {0}; text-align: right;&quot;&gt;{1}&lt;/td&gt;&#39; -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>&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=","")
            # 仅输出对象;它将在变量 $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

使用虚假数据,表格应如下所示:

Powershell 动态 HTML 表格

英文:

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 = &#39;#000000&#39;,
[string]$BackColorOddRow = &#39;#305496&#39;
)
# 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(&#39;&lt;table&gt;&#39;)
if ($null -ne $InputObject) {
if (([object]$InputObject).GetType().FullName -eq &#39;System.Data.DataTable&#39;){
# 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(&#39;&lt;thead&gt;&lt;tr&gt;&#39;)
foreach ($column in $headers) {
[void]$sb.AppendLine((&#39;&lt;th&gt;{0}&lt;/th&gt;&#39; -f [System.Web.HttpUtility]::HtmlEncode($column)))
}
[void]$sb.AppendLine(&#39;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&#39;)
$row = 0
$InputObject | ForEach-Object {
# add inline style for zebra color rows
if ($row++ -band 1) {
$tr = &#39;&lt;tr style=&quot;background-color: {0};&quot;&gt;&#39; -f $BackColorOddRow
} 
else {
$tr = &#39;&lt;tr&gt;&#39;
}
[void]$sb.AppendLine($tr)
foreach ($column in $headers) {
[string]$val = $($_.$column)
if ($column -eq &#39;Last Result&#39; -and $val -match &#39;^\d+$&#39;) {
# special case, if column is &#39;Last Result&#39; and $val is all numeric
# and $val equals 0, use backcolor green else red
$resultColor = if ([int]$val -eq 0) { &#39;#92D050&#39; } else { &#39;#FF4606&#39; }
$td = &#39;&lt;td style=&quot;background-color: {0}; text-align: right;&quot;&gt;{1}&lt;/td&gt;&#39; -f $resultColor, $val
}
else {
if ([string]::IsNullOrWhiteSpace($val)) { 
$td = &#39;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&#39; 
} 
else { 
$td = &#39;&lt;td&gt;{0}&lt;/td&gt;&#39; -f [System.Web.HttpUtility]::HtmlEncode($val)
}
}
[void]$sb.Append($td)
}
[void]$sb.AppendLine(&#39;&lt;/tr&gt;&#39;)
}
[void]$sb.AppendLine(&#39;&lt;/tbody&gt;&#39;)
}
[void]$sb.AppendLine(&#39;&lt;/table&gt;&#39;)
return $sb.ToString()
}
$style = @&quot;
&lt;style&gt;
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;}
&lt;/style&gt;
&quot;@
$mailTemplate = @&quot;
&lt;html&gt;&lt;head&gt;
{0}
&lt;/head&gt;&lt;body&gt;
This an automated message.&lt;br /&gt;&lt;br /&gt;
{1}
&lt;br /&gt;
Please review the attachment.&lt;br /&gt;&lt;br /&gt;Thank you.
&lt;/body&gt;&lt;/html&gt;
&quot;@
$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(&quot;,&quot;)[1].Replace(&quot;CN=&quot;,&quot;&quot;)
# just output the object; it will be collected in variable $results
[PsCustomObject] @{
&#39;Source DC&#39;    = $DC.HostName.ToUpper()
&#39;Partner DC&#39;   = (Get-ADComputer $Partner).DNSHostName.ToUpper()
&#39;Direction&#39;    = $ReplStatus.PartnerType
&#39;Type&#39;         = $ReplStatus.IntersiteTransportType
&#39;Last Attempt&#39; = $ReplStatus.LastReplicationAttempt
&#39;Last Success&#39; = $ReplStatus.LastReplicationSuccess
&#39;Last Result&#39;  = $ReplStatus.LastReplicationResult
}
}
} 
else {
[PsCustomObject] @{
&#39;Source DC&#39;    = $DC.HostName.ToUpper()
&#39;Partner DC&#39;   = &quot;N/A&quot;
&#39;Direction&#39;    = &quot;N/A&quot;
&#39;Type&#39;         = &quot;N/A&quot;
&#39;Last Attempt&#39; = &quot;N/A&quot;
&#39;Last Success&#39; = &quot;N/A&quot;
&#39;Last Result&#39;  = &quot;N/A&quot;
}
}
}
# use our own function to custom format the HTML table
$table = ConvertTo-HTMLTable -InputObject $results -BackColorHeader &#39;#000000&#39; -BackColorOddRow &#39;#305496&#39;
$mailParams = @{
To         = &#39;user@contoso.com&#39;
From       = &#39;user@contoso.com&#39;
Subject    = &#39;AD Status&#39;
Body       = $mailTemplate -f $style , $table
BodyAsHtml = $true
Priority   = &#39;High&#39;
SmtpServer = &#39;smtp.contoso.com&#39;
Encoding   = &#39;UTF8&#39;
}
Send-MailMessage @mailParams

Using fake data, the table should look like this:

Powershell 动态 HTML 表格

huangapple
  • 本文由 发表于 2023年1月9日 16:45:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定