How to generate an HTML report using PowerShell?

Microsoft TechnologiesSoftware & CodingPowerShell

To generate an HTML report using PowerShell, we can use the ConvertTo-HTML command. For example, let say we need to get the services to report in HTML format then we can use ConvertTo-HTML as a pipeline.

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

The first command will retrieve the output in the HTML file and the second command (ii) is the alias of the Invoke-Item command.

Once you check the output,

It selects all the properties of the command. To select only a few properties, you can either use the Select command or use the -Property parameter in the ConvertTo-Html command. Both the commands are shown below.

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

OR,

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

Output

You can also use the below parameters to make HTML output more proper.

  • -Head − To provide the heading.

  • -PreContent − For the table description.

  • -PostContent − Description at the bottom.

  • -Title − Title of the WebPage.

Example,

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

Output

If you make the output more stylish, you can apply CSS code as shown below.

Code

$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

Output

raja
Published on 01-Sep-2021 08:13:28
Advertisements