如何使用 PowerShell 生成 HTML 報告?


要使用 PowerShell 生成 HTML 報告,我們可以使用 **ConvertTo-HTML 命令**。例如,假設我們需要將服務輸出到 HTML 格式,則可以使用 **ConvertTo-HTML** 作為管道。

Get-Service | ConvertTo-Html | Out-File C:\Temp\Services.html
ii C:\Temp\services.html

第一個命令將把輸出儲存到 HTML 檔案中,第二個命令 (ii) 是 **Invoke-Item** 命令的別名。

檢查輸出後,

它會選擇命令的所有屬性。要僅選擇一些屬性,可以使用 Select 命令或在 **ConvertTo-Html** 命令中使用 **-Property** 引數。下面顯示了這兩個命令。

Get-Service | Select Name, StartType, Status | ConvertTo-Html | OutFile C:\Temp\services.html

或者,

Get-Service | ConvertTo-Html -Property Name, StartType, Status | OutFile C:\Temp\services.html

輸出

您還可以使用以下引數使 HTML 輸出更規範。

  • **-Head** - 用於提供標題。

  • **-PreContent** - 用於表格描述。

  • **-PostContent** - 用於底部描述。

  • **-Title** - 網頁標題。

示例,

Get-Service |Select -Last 5| ConvertTo-Html -Property Name, StartType, Status `
   -PreContent "<h3>Services Output</h3>" `
   -PostContent "<h3>Generated Date: $(Get-Date)/<h3>" `
   -Title "Services Information" `
   -Head "<h1><center>LocalHost Services Information</center></h1>" `
      | Out-File C:\Temp\services.html
ii C:\Temp\services.html

輸出

如果要使輸出更具樣式,可以應用如下所示的 CSS 程式碼。

程式碼

$header = @"
<style>
   table, th, td {
      border-style: solid;
      border-collapse: collapse;
   }

   h3 {
      color: Blue
   }

<style>
"@

Get-Service |Select -Last 5| ConvertTo-Html -Property Name, StartType, Status `
   -PreContent "<h3>Services Output</h3>" `
   -PostContent "<h3>Generated Date: $(Get-Date)</h3>" `
   -Title "Services Information" `
   -Head $header `
      | Out-File C:\Temp\services.html
ii C:\Temp\services.html

輸出

更新於: 2021年9月1日

5K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告