Powershell动态HTML表

3ks5zfa0  于 2023-01-26  发布在  Shell
关注(0)|答案(1)|浏览(135)

我有以下(部分)脚本,它获取AD复制状态的内容并将其格式化为表格,然后通过电子邮件发送。
我的问题是:我想创建一个动态的HTML表格,就像我想要的输出。我们怎么做呢?
如果最后结果等于0,我希望该单元格的颜色为绿色,如果大于0,则应为红色。
我想要的输出:

下面是我的脚本:

$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

编辑1:

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
            }
ubby3x7f

ubby3x7f1#

我想我会使用自己的自定义函数将$results中的数据转换为HTML表格。
我尝试模仿示例图像中的样式,并对代码做了一些小的调整

# 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

使用伪数据时,该表应如下所示:

相关问题