Powershell 动态 HTML 表格

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

Powershell dynamic HTML table

问题

  1. if ($column -eq 'Last Result' -and $val -match '^\d+$') {
  2. # 特殊情况,如果列是 'Last Result' 且 $val 是全数字,且 $val 等于 0,使用背景颜色绿色,否则为红色
  3. $resultColor = if ([int]$val -eq 0) { '#92D050' } else { '#FF4606' }
  4. $td = '<td style="background-color: {0}; text-align: right;">{1}</td>' -f $resultColor, $val
  5. }
  6. elseif ($column -eq 'Last Result1' -and $val -match '^\d+$') {
  7. # 特殊情况,如果列是 'Last Result1' 且 $val 是全数字,且 $val 等于 0,使用背景颜色绿色,否则为红色
  8. $resultColor = if ([int]$val -eq 0) { '#92D050' } else { '#FF4606' }
  9. $td = '<td style="background-color: {0}; text-align: right;">{1}</td>' -f $resultColor, $val
  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 :

Powershell 动态 HTML 表格

Here is my script :

  1. $style = @&quot;
  2. &lt;style&gt;
  3. body, table {font-family: sans-serif; font-size: 11pt; color: #1F497D;}
  4. table {border: 1px solid black; border-collapse: collapse; color: #000000;}
  5. th {border: 1px solid black; background: #dddddd; padding: 3px;}
  6. td {border: 1px solid black; padding: 3px;}
  7. &lt;/style&gt;
  8. &quot;@
  9. $mailTemplate = @&quot;
  10. &lt;html&gt;&lt;head&gt;{0}&lt;/head&gt;&lt;body&gt;
  11. This an automated message.&lt;br /&gt;
  12. {1}
  13. Please review the attachment.&lt;br /&gt;&lt;br /&gt;Thank you.
  14. &lt;/body&gt;&lt;/html&gt;
  15. &quot;@
  16. $DCs = Get-ADDomainController -Filter * |sort name
  17. $results = @()
  18. ForEach ($DC in $DCs) {
  19. $ReplStatuses = Get-ADReplicationPartnerMetadata -target $DC.HostName -PartnerType Both -ErrorAction SilentlyContinue
  20. If ($ReplStatuses) {
  21. ForEach ($ReplStatus in $ReplStatuses) {
  22. $Partner = $ReplStatus.Partner.Split(&quot;,&quot;)[1].Replace(&quot;CN=&quot;,&quot;&quot;)
  23. $results += [pscustomobject] @{
  24. &#39;Source DC&#39; = $DC.HostName.ToUpper()
  25. &#39;Partner DC&#39; = (Get-ADComputer $Partner).DNSHostName.ToUpper()
  26. Direction = $ReplStatus.PartnerType
  27. Type = $ReplStatus.IntersiteTransportType
  28. &#39;Last Attempt&#39; = $ReplStatus.LastReplicationAttempt
  29. &#39;Last Success&#39; = $ReplStatus.LastReplicationSuccess
  30. &#39;Last Result&#39; = $ReplStatus.LastReplicationResult
  31. }
  32. }
  33. } Else {
  34. $results += [pscustomobject] @{
  35. &#39;Source DC&#39; = $DC.HostName.ToUpper()
  36. &#39;Partner DC&#39; = &quot;N/A&quot;
  37. Direction = &quot;N/A&quot;
  38. Type = &quot;N/A&quot;
  39. &#39;Last Attempt&#39; = &quot;N/A&quot;
  40. &#39;Last Success&#39; = &quot;N/A&quot;
  41. &#39;Last Result&#39; = &quot;N/A&quot;
  42. }
  43. }
  44. }
  45. $table = ($results | ConvertTo-Html -As Table -Fragment) -join [environment]::NewLine
  46. $mailParams = @{
  47. To = &#39;user@contoso.com&#39;
  48. From = &#39;user@contoso.com&#39;
  49. Subject = &#39;AD Status&#39;
  50. Body = $mailTemplate -f $style , $table
  51. BodyAsHtml = $true
  52. Priority = &#39;High&#39;
  53. SmtpServer = &#39;&#39;
  54. Encoding = &#39;UTF8&#39;
  55. }
  56. Send-MailMessage @mailParams

EDIT1:

  1. if ($column -eq &#39;Last Result&#39; -and $val -match &#39;^\d+$&#39;) {
  2. # special case, if column is &#39;Last Result&#39; and $val is all numeric
  3. # and $val equals 0, use backcolor green else red
  4. $resultColor = if ([int]$val -eq 0) { &#39;#92D050&#39; } else { &#39;#FF4606&#39; }
  5. $td = &#39;&lt;td style=&quot;background-color: {0}; text-align: right;&quot;&gt;{1}&lt;/td&gt;&#39; -f $resultColor, $val
  6. }
  7. elseif $column -eq &#39;Last Result1&#39; -and $val -match &#39;^\d+$&#39;) {
  8. # special case, if column is &#39;Last Result1&#39; and $val is all numeric
  9. # and $val equals 0, use backcolor green else red
  10. $resultColor = if ([int]$val -eq 0) { &#39;#92D050&#39; } else { &#39;#FF4606&#39; }
  11. $td = &#39;&lt;td style=&quot;background-color: {0}; text-align: right;&quot;&gt;{1}&lt;/td&gt;&#39; -f $resultColor, $val
  12. }

答案1

得分: 0

我猜我会使用自定义函数将数据转换为HTML表格。

我尝试模仿您示例图像中的样式,并对您的代码进行了一些小调整。

  1. # 自定义函数以将数据转换为HTML表格
  2. function ConvertTo-HTMLTable {
  3. [CmdletBinding()]
  4. param (
  5. [Parameter(Mandatory = $true, Position = 0)]
  6. $InputObject,
  7. [string]$BackColorHeader = '#000000',
  8. [string]$BackColorOddRow = '#305496'
  9. )
  10. # 接受 System.Data.DataTable 对象或 PSObject 数组并将其转换为带样式的HTML表格
  11. # 添加类型以将HTML特殊字符替换为实体
  12. Add-Type -AssemblyName System.Web
  13. $sb = New-Object -TypeName System.Text.StringBuilder
  14. [void]$sb.AppendLine('<table>')
  15. if ($null -ne $InputObject) {
  16. if (([object]$InputObject).GetType().FullName -eq 'System.Data.DataTable'){
  17. # 它是一个 DataTable;将其转换为 PSObject 数组
  18. $InputObject = $InputObject | Select-Object * -ExcludeProperty ItemArray, Table, RowError, RowState, HasErrors
  19. }
  20. $headers = $InputObject[0].PSObject.Properties | Select -ExpandProperty Name
  21. [void]$sb.AppendLine('<thead><tr>')
  22. foreach ($column in $headers) {
  23. [void]$sb.AppendLine(("<th>{0}</th>" -f [System.Web.HttpUtility]::HtmlEncode($column)))
  24. }
  25. [void]$sb.AppendLine('</tr></thead><tbody>')
  26. $row = 0
  27. $InputObject | ForEach-Object {
  28. # 添加斑马纹颜色行的内联样式
  29. if ($row++ -band 1) {
  30. $tr = "<tr style='background-color: {0};'>" -f $BackColorOddRow
  31. }
  32. else {
  33. $tr = "<tr>"
  34. }
  35. [void]$sb.AppendLine($tr)
  36. foreach ($column in $headers) {
  37. [string]$val = $($_.$column)
  38. if ($column -eq 'Last Result' -and $val -match '^\d+$') {
  39. # 特殊情况,如果列是'Last Result'并且$val全为数字
  40. # 如果$val等于0,使用背景颜色绿色,否则红色
  41. $resultColor = if ([int]$val -eq 0) { '#92D050' } else { '#FF4606' }
  42. $td = ("<td style='background-color: {0}; text-align: right;'>{1}</td>" -f $resultColor, $val)
  43. }
  44. else {
  45. if ([string]::IsNullOrWhiteSpace($val)) {
  46. $td = "<td>&nbsp;</td>"
  47. }
  48. else {
  49. $td = "<td>{0}</td>" -f [System.Web.HttpUtility]::HtmlEncode($val)
  50. }
  51. }
  52. [void]$sb.Append($td)
  53. }
  54. [void]$sb.AppendLine('</tr>')
  55. }
  56. [void]$sb.AppendLine('</tbody>')
  57. }
  58. [void]$sb.AppendLine('</table>')
  59. return $sb.ToString()
  60. }
  61. $style = @"
  62. <style>
  63. body, table {font-family: sans-serif; font-size: 11pt; color: #000000;}
  64. table {border: 1px solid black; border-collapse: collapse; color: #ffffff;}
  65. tr {background-color: #4472C4;}
  66. th {border: 1px solid black; background-color: #000000; padding: 3px; font-weight:normal; text-align: left;}
  67. td {border: 1px solid black; padding: 3px;}
  68. </style>
  69. "@
  70. $mailTemplate = @"
  71. <html><head>
  72. {0}
  73. </head><body>
  74. This an automated message.<br /><br />
  75. {1}
  76. <br />
  77. Please review the attachment.<br /><br />Thank you.
  78. </body></html>
  79. "@
  80. $DCs = Get-ADDomainController -Filter * | Sort-Object name
  81. $results = foreach ($DC in $DCs) {
  82. $ReplStatuses = Get-ADReplicationPartnerMetadata -target $DC.HostName -PartnerType Both -ErrorAction SilentlyContinue
  83. If ($ReplStatuses) {
  84. foreach ($ReplStatus in $ReplStatuses) {
  85. $Partner = $ReplStatus.Partner.Split(",")[1].Replace("CN=","")
  86. # 仅输出对象;它将在变量 $results 中收集
  87. [PsCustomObject] @{
  88. 'Source DC' = $DC.HostName.ToUpper()
  89. 'Partner DC' = (Get-ADComputer $Partner).DNSHostName.ToUpper()
  90. 'Direction' = $ReplStatus.PartnerType
  91. 'Type' = $ReplStatus.IntersiteTransportType
  92. 'Last Attempt' = $ReplStatus.LastReplicationAttempt
  93. 'Last Success' = $ReplStatus.LastReplicationSuccess
  94. 'Last Result' = $ReplStatus.LastReplicationResult
  95. }
  96. }
  97. }
  98. else {
  99. [PsCustomObject] @{
  100. 'Source DC' = $DC.HostName.ToUpper()
  101. 'Partner DC' = "N/A"
  102. 'Direction' = "N/A"
  103. 'Type' = "N/A"
  104. 'Last Attempt' = "N/A"
  105. 'Last Success' = "N/A"
  106. 'Last Result' = "N/A"
  107. }
  108. }
  109. }
  110. # 使用我们自己的函数来自定义格式化HTML表格
  111. $table = ConvertTo-HTMLTable -InputObject $results -BackColorHeader '#000000' -BackColorOddRow '#305496'
  112. $mailParams = @{
  113. To = 'user@contoso.com'
  114. From = 'user@contoso.com'
  115. Subject = 'AD Status'
  116. Body = $mailTemplate -f $style , $table
  117. BodyAsHtml = $true
  118. Priority = 'High'
  119. SmtpServer = 'smtp.contoso.com'
  120. Encoding = 'UTF8'
  121. }
  122. 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

  1. # a custom function to convert the data to HTML table
  2. function ConvertTo-HTMLTable {
  3. [CmdletBinding()]
  4. param (
  5. [Parameter(Mandatory = $true, Position = 0)]
  6. $InputObject,
  7. [string]$BackColorHeader = &#39;#000000&#39;,
  8. [string]$BackColorOddRow = &#39;#305496&#39;
  9. )
  10. # Accepts a System.Data.DataTable object or an array of PSObjects and converts to styled HTML table
  11. # add type needed to replace HTML special characters into entities
  12. Add-Type -AssemblyName System.Web
  13. $sb = New-Object -TypeName System.Text.StringBuilder
  14. [void]$sb.AppendLine(&#39;&lt;table&gt;&#39;)
  15. if ($null -ne $InputObject) {
  16. if (([object]$InputObject).GetType().FullName -eq &#39;System.Data.DataTable&#39;){
  17. # it is a DataTable; convert to array of PSObjects
  18. $InputObject = $InputObject | Select-Object * -ExcludeProperty ItemArray, Table, RowError, RowState, HasErrors
  19. }
  20. $headers = $InputObject[0].PSObject.Properties | Select -ExpandProperty Name
  21. [void]$sb.AppendLine(&#39;&lt;thead&gt;&lt;tr&gt;&#39;)
  22. foreach ($column in $headers) {
  23. [void]$sb.AppendLine((&#39;&lt;th&gt;{0}&lt;/th&gt;&#39; -f [System.Web.HttpUtility]::HtmlEncode($column)))
  24. }
  25. [void]$sb.AppendLine(&#39;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&#39;)
  26. $row = 0
  27. $InputObject | ForEach-Object {
  28. # add inline style for zebra color rows
  29. if ($row++ -band 1) {
  30. $tr = &#39;&lt;tr style=&quot;background-color: {0};&quot;&gt;&#39; -f $BackColorOddRow
  31. }
  32. else {
  33. $tr = &#39;&lt;tr&gt;&#39;
  34. }
  35. [void]$sb.AppendLine($tr)
  36. foreach ($column in $headers) {
  37. [string]$val = $($_.$column)
  38. if ($column -eq &#39;Last Result&#39; -and $val -match &#39;^\d+$&#39;) {
  39. # special case, if column is &#39;Last Result&#39; and $val is all numeric
  40. # and $val equals 0, use backcolor green else red
  41. $resultColor = if ([int]$val -eq 0) { &#39;#92D050&#39; } else { &#39;#FF4606&#39; }
  42. $td = &#39;&lt;td style=&quot;background-color: {0}; text-align: right;&quot;&gt;{1}&lt;/td&gt;&#39; -f $resultColor, $val
  43. }
  44. else {
  45. if ([string]::IsNullOrWhiteSpace($val)) {
  46. $td = &#39;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&#39;
  47. }
  48. else {
  49. $td = &#39;&lt;td&gt;{0}&lt;/td&gt;&#39; -f [System.Web.HttpUtility]::HtmlEncode($val)
  50. }
  51. }
  52. [void]$sb.Append($td)
  53. }
  54. [void]$sb.AppendLine(&#39;&lt;/tr&gt;&#39;)
  55. }
  56. [void]$sb.AppendLine(&#39;&lt;/tbody&gt;&#39;)
  57. }
  58. [void]$sb.AppendLine(&#39;&lt;/table&gt;&#39;)
  59. return $sb.ToString()
  60. }
  61. $style = @&quot;
  62. &lt;style&gt;
  63. body, table {font-family: sans-serif; font-size: 11pt; color: #000000;}
  64. table {border: 1px solid black; border-collapse: collapse; color: #ffffff;}
  65. tr {background-color: #4472C4;}
  66. th {border: 1px solid black; background-color: #000000; padding: 3px; font-weight:normal; text-align: left;}
  67. td {border: 1px solid black; padding: 3px;}
  68. &lt;/style&gt;
  69. &quot;@
  70. $mailTemplate = @&quot;
  71. &lt;html&gt;&lt;head&gt;
  72. {0}
  73. &lt;/head&gt;&lt;body&gt;
  74. This an automated message.&lt;br /&gt;&lt;br /&gt;
  75. {1}
  76. &lt;br /&gt;
  77. Please review the attachment.&lt;br /&gt;&lt;br /&gt;Thank you.
  78. &lt;/body&gt;&lt;/html&gt;
  79. &quot;@
  80. $DCs = Get-ADDomainController -Filter * | Sort-Object name
  81. $results = foreach ($DC in $DCs) {
  82. $ReplStatuses = Get-ADReplicationPartnerMetadata -target $DC.HostName -PartnerType Both -ErrorAction SilentlyContinue
  83. If ($ReplStatuses) {
  84. foreach ($ReplStatus in $ReplStatuses) {
  85. $Partner = $ReplStatus.Partner.Split(&quot;,&quot;)[1].Replace(&quot;CN=&quot;,&quot;&quot;)
  86. # just output the object; it will be collected in variable $results
  87. [PsCustomObject] @{
  88. &#39;Source DC&#39; = $DC.HostName.ToUpper()
  89. &#39;Partner DC&#39; = (Get-ADComputer $Partner).DNSHostName.ToUpper()
  90. &#39;Direction&#39; = $ReplStatus.PartnerType
  91. &#39;Type&#39; = $ReplStatus.IntersiteTransportType
  92. &#39;Last Attempt&#39; = $ReplStatus.LastReplicationAttempt
  93. &#39;Last Success&#39; = $ReplStatus.LastReplicationSuccess
  94. &#39;Last Result&#39; = $ReplStatus.LastReplicationResult
  95. }
  96. }
  97. }
  98. else {
  99. [PsCustomObject] @{
  100. &#39;Source DC&#39; = $DC.HostName.ToUpper()
  101. &#39;Partner DC&#39; = &quot;N/A&quot;
  102. &#39;Direction&#39; = &quot;N/A&quot;
  103. &#39;Type&#39; = &quot;N/A&quot;
  104. &#39;Last Attempt&#39; = &quot;N/A&quot;
  105. &#39;Last Success&#39; = &quot;N/A&quot;
  106. &#39;Last Result&#39; = &quot;N/A&quot;
  107. }
  108. }
  109. }
  110. # use our own function to custom format the HTML table
  111. $table = ConvertTo-HTMLTable -InputObject $results -BackColorHeader &#39;#000000&#39; -BackColorOddRow &#39;#305496&#39;
  112. $mailParams = @{
  113. To = &#39;user@contoso.com&#39;
  114. From = &#39;user@contoso.com&#39;
  115. Subject = &#39;AD Status&#39;
  116. Body = $mailTemplate -f $style , $table
  117. BodyAsHtml = $true
  118. Priority = &#39;High&#39;
  119. SmtpServer = &#39;smtp.contoso.com&#39;
  120. Encoding = &#39;UTF8&#39;
  121. }
  122. 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:

确定