Home > Software engineering >  Powershell dynamic HTML table
Powershell dynamic HTML table

Time:01-10

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 :

enter image description here

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         = '[email protected]'
        From       = '[email protected]'
        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
            }

CodePudding user response:

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         = '[email protected]'
    From       = '[email protected]'
    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:

enter image description here

  • Related