ConvertTo-HTML参数无法正常运行

时间:2018-08-03 09:43:47

标签: powershell

我正在尝试编写PowerShell文件的脚本,以使用以下CMD命令分析Exchange配置:

PowerShell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V15\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; . 'C:\test2.ps1' | ConvertTo-Html | Out-File -FilePath C:\test.html"

Test2.ps1代码:

Write-Output "Test"
Get-SenderIDConfig | fl -Property Enabled
Get-SenderReputationConfig | fl -Property SenderBlockingEnabled
Write-Output "List All SendConnectors"
Get-SendConnector
Write-Output "Ignoe STARTTLS SendConnectors"
Get-SendConnector | fl -Property IgnoreSTARTTLS

通过直接将输出重定向到TXT文件(>> output.txt),输出效果很好,但是问题是我使用ConvertTo-HTML得到了不可读的输出,如下图所示:

enter image description here

编辑:这是想要的结果

enter image description here

1 个答案:

答案 0 :(得分:1)

您不能将这样的输入传递给ConvertTo-Html并期望cmdlet神奇地生成所需格式的报告。该cmdlet不能那样工作。通常用于将相同类型的对象列表转换为表格输出,例如您可以获取Get-SendConnector的输出并从中创建一个HTML表:

Get-SendConnector | Select-Object Identity, AddressSpaces, Enabled | ConvertTo-Html

但是,它本身将创建一个完整的HTML页面。由于还需要页面中的其他(非表格)数据,因此可以将表创建为 fragment ,并将该数据和其他数据插入到字符串模板中,例如像这样:

$head = @'
<style>
/* put style definitions here */
h1 { font-size: 20px; }
h2 { font-size: 16px; }
/* ... */
</style>
'@

$fragments = @()
$fragments += '<p>Enabled: {0}</p>' -f (Get-SenderIDConfig).Enabled
$fragments += '<p>SenderBlockingEnabled: {0}</p>' -f (Get-SenderReputationConfig).SenderBlockingEnabled
$fragments += Get-SendConnector |
              Select-Object Identity, AddressSpaces, Enabled |
              ConvertTo-Html -Fragment -PreContent '<h2>List All SendConnectors</h2>'
$fragments += Get-SendConnector |
              Select-Object Identity, IgnoreSTARTTLS |
              ConvertTo-Html -Fragment -PreContent '<h2>Ignore STARTTLS Connectory</h2>'

ConvertTo-Html -Head $head -PreContent '<h1>Test</h1>' -PostContent $fragments |
    Set-Content 'output.html'

有关更多信息,请参见this Scripting Guy article

您还可以构建自己的HTML模板并将其填充为值:

$template = @'
<html>
<head>
<style>...</style>
</head>
<body>
<p>Enabled: {0}</p>
<p>SenderBlockingEnabled: {1}</p>
{2}
{3}
</body>
</html>
'@

$enabled         = (Get-SenderIDConfig).Enabled
$blockingEnabled = (Get-SenderReputationConfig).SenderBlockingEnabled
$connectors      = Get-SendConnector |
                   Select-Object Identity, AddressSpaces, Enabled |
                   ConvertTo-Html -Fragment -PreContent '<h2>List All SendConnectors</h2>' |
                   Out-String
$ignoreSTARTTLS  = Get-SendConnector |
                   Select-Object Identity, IgnoreSTARTTLS |
                   ConvertTo-Html -Fragment -PreContent '<h2>Ignore STARTTLS Connectory</h2>' |
                   Out-String

$template -f $enabled, $blockingEnabled, $connectors, $ignoreSTARTTLS |
    Set-Content 'output.html'