首页 > 解决方案 > 如何格式化相对于表头的行?

问题描述

我有一个脚本如下:

$ebody = "
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
<table style=`"width:100%`">
    <tr>
        <th></th>
        <th>Data Source</th>
        <th>dest Server</th>
        <th>Security Option</th>
        <th>Est Size</th>
        <th>Last Updated</th>
    </tr>
</table>
"
for ($i = 0; $i -lt 3; $i++)
{
    $ebody += "
    <style>
    table, th, td {
      border: 1px solid black;
      border-collapse: collapse;
    }
    </style>
    <table style=`"width:100%`">
        <tr>
            <td>$($i)</td>
            <td>$DSource</td>
            <td>$Server</td>
            <td>$Security</td>
            <td>$Size</td>
            <td>$Updated</td>
        </tr>
    </table>
    "
if ($i -gt 1)
{Send-MailMessage -To recipient@domain.com -from sender@domain.com -Subject "hi" -body $ebody -BAH -SmtpServer server@domain.com -Port 25 -Credential $cred -usessl}
}

我将其作为电子邮件的输出:

桌子

我想得到这种输出,

想要的

其中行相对于标题进行调整......或者如果有一种方法可以将标题调整为行,但我认为除非有某种参考方式,否则这是不可能的?

所以基本上我可以通过我的脚本要求将 $ebody 附加到行来实现一个好的相对填充的表吗?

编辑:从 Theo 的答案中应用 $ebody 更改后。第一个迭代行完全对齐!但不知何故第二次迭代没有......

编辑

标签: htmlpowershell

解决方案


不确定您从哪里获取数据,但现在,在下面的示例中,我只是假设代码中的给定变量是数组。如果不是这种情况,请告诉我,以便我们可以在循环内进行调整。

首先,您不必添加<style>循环内部。在身体开始时这样做一次就足够了。
接下来,只要您有数据,就在该表上构建,最后关闭该表。

我对 Send-MailMessage cmdlet 中的所有参数使用了 splatting,以使代码更易读。

$ebody = @'
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <style>
            table, th, td {
              border: 1px solid black;
              border-collapse: collapse;
            }
        </style>
    </head>
    <body>
    <table style="width:100%">
        <tr>
            <th></th>
            <th>Data Source</th>
            <th>dest Server</th>
            <th>Security Option</th>
            <th>Est Size</th>
            <th>Last Updated</th>
        </tr>

'@

for ($i = 0; $i -lt 3; $i++) {
    $ebody += @"
            <tr>
                <td>$i</td>
                <td>$DSource[$i]</td>
                <td>$Server[$i]</td>
                <td>$Security[$i]</td>
                <td>$Size[$i]</td>
                <td>$Updated[$i]</td>
            </tr>

"@
}

$ebody += @"
        </table>
    </body>
</html>
"@

if ($i -gt 1) {
    $params = @{
        'To'         = 'recipient@domain.com'
        'From'       = 'sender@domain.com'
        'Subject'    = 'hi'
        'Body'       = $ebody
        'BodyAsHtml' = $true
        'SmtpServer' = 'server.domain.com'
        'Port'       = 25
        'Credential' = $cred
        'UseSsl'     = $true
    }

    Send-MailMessage @params
}

推荐阅读