ConvertTo Html - PowerShell


Overview

ConvertTo-Html converts text files, objects, or variables to HTML format, enabling easy presentation of data in web pages or dashboards. It offers customizable options for formatting, styling, and output control.

Syntax

ConvertTo-Html [-InputObject] <object> [-FileName] <string> [-Append] [-PreContent] <string> [-PostContent] <string> [-Fragment] [-Head] <string> [-Css] <string> [-Style] <string> [-InlineStyle] [-IconUrl] <string> [-Title] <string> [-Charset] <string> [-Render] [-Force] [-NoWrap] [-Width] <int> [-PassThru] [-WhatIf] [-Confirm]

Options/Flags

  • -InputObject: Specifies the object or variable to convert to HTML.
  • -FileName: Sets the output filename for the HTML document.
  • -Append: Appends the HTML output to the specified file instead of overwriting.
  • -PreContent: Inserts text or HTML before the converted content.
  • -PostContent: Inserts text or HTML after the converted content.
  • -Fragment: Outputs only the body content of the HTML, without HTML tags.
  • -Head: Customizes the HTML head section by providing HTML code.
  • -Css: Specifies a CSS file or inline style sheet for formatting.
  • -Style: Inline CSS styles to be applied to the output.
  • -InlineStyle: Outputs CSS styles within the HTML document instead of using a separate file.
  • -IconUrl: Sets the URL for the icon to be displayed in the browser.
  • -Title: Defines the title of the HTML document.
  • -Charset: Specifies the character set encoding for the HTML output.
  • -Render: Renders the output in a browser.
  • -Force: Overwrites the output file if it already exists.
  • -NoWrap: Prevents line-wrapping in the HTML output.
  • -Width: Sets the maximum width for the output in pixels.
  • -PassThru: Returns the converted HTML object as a string.
  • -WhatIf: Shows what would be converted without actually performing the conversion.
  • -Confirm: Prompts for confirmation before performing the conversion.

Examples

Convert a text file to HTML:

ConvertTo-Html -InputObject txt_file.txt -FileName html_file.html

Convert a PowerShell object to HTML, appending to an existing file:

ConvertTo-Html -InputObject $object -FileName html_file.html -Append

Create an HTML fragment with custom head section and CSS:

ConvertTo-Html -InputObject $object -Fragment -Head " " -Css "styles.css"

Common Issues

  • File not created or overwritten: Ensure you have write permissions for the output file and use -Force to overwrite an existing file.
  • Formatting issues: Use -Css or -Style to customize the formatting.
  • Browser rendering problems: Check if the browser supports the specified CSS or character encoding.

Integration

Convert PowerShell transcripts to HTML for documentation:

$transcript | ConvertTo-Html -FileName transcript.html

Generate interactive HTML reports with CSS:

Get-ChildItem | ConvertTo-Html -Css report-styles.css | Invoke-Item