在Powershell中使用HTML创建表

时间:2016-08-17 08:47:43

标签: powershell powershell-v2.0

我想知道服务已停止,哪些设置为自动,输出文件转到HTML页面。在该HTML输出中,我想在该表服务器名称之上创建已停止服务的表。有人能告诉我..

$ServerListFile = "C:\Dv\Server_List.txt" 
$ServerList = Get-Content $ServerListFile -ErrorAction SilentlyContinue
foreach ($Computername in $ServerList) {
Write-Host "Automatic Services Stopped :" $Computername 
Get-wmiobject win32_service -computername $Computername  -Filter  "startmode  
= 'auto'  AND state != 'running'" | Select DisplayName,Name,State,startmode  
|  Format-Table  -auto | Out-File C:\Dv\Report.html
}

1 个答案:

答案 0 :(得分:3)

这样的事情应该有效。

单人表

Get-Content "C:\Dv\Server_List.txt" -ErrorAction SilentlyContinue | ForEach-Object {
    Write-Host "Automatic Services Stopped :" $_ 
    Get-WmiObject Win32_Service -ComputerName $_ -Filter  "startmode = 'auto' AND state != 'running'"
} |
    Select-Object DisplayName, Name, State, StartMode |
    ConvertTo-Html |
    Out-File C:\Dv\Report.html

多个表格

此版本使用ConvertTo-Html -Fragment创建一系列表格。每个表前面都有一个带有计算机名称的HTML标头(示例中为h2)。使用对ConvertTo-Html的裸(无输入)调用将各个表连接并合并为单个HTML文档。

# Generate the content which should be inserted as a set of HTML tables
$preContent = Get-Content "C:\Dv\Server_List.txt" -ErrorAction SilentlyContinue | ForEach-Object {
    $ComputerName = $_

    Write-Host "Automatic Services Stopped :" $ComputerName 

    # A table (and heading) will only be generated for $ComputerName if there are services matching the filter. 
    Get-WmiObject Win32_Service -ComputerName $ComputerName -Filter  "startmode = 'auto' AND state != 'running'" |
        Select-Object DisplayName, Name, State, StartMode |
        ConvertTo-Html -PreContent "<h2>$ComputerName</h2>" -Fragment
}

# Generate the document which holds all of the individual tables.
$htmlDocument = ConvertTo-Html -Head $htmlHead -PreContent $preContent | Out-String
# Because the document has no input object it will have an empty table (<table></table>), this should be removed.
$htmlDocument -replace '<table>\r?\n</table>' | Out-File C:\Dv\Report.html

<强>定型

您会发现这些HTML生成的HTML非常原始。解决这个问题的一个更好的方法是使用CSS,这是我的一个片段,它使HTML表看起来更漂亮:

$HtmlHead = '<style>
    body {
        background-color: white;
        font-family:      "Calibri";
    }

    table {
        border-width:     1px;
        border-style:     solid;
        border-color:     black;
        border-collapse:  collapse;
        width:            100%;
    }

    th {
        border-width:     1px;
        padding:          5px;
        border-style:     solid;
        border-color:     black;
        background-color: #98C6F3;
    }

    td {
        border-width:     1px;
        padding:          5px;
        border-style:     solid;
        border-color:     black;
        background-color: White;
    }

    tr {
        text-align:       left;
    }
</style>'

# Use the Head parameter when calling ConvertTo-Html
... | ConvertTo-Html -Head $HtmlHead | ...

注意:Head仅在ConvertTo-Html提供的Fragment参数时适用。