Convert HTML to Plain Text in PowerShell
Step-by-step instructions for converting HTML to plain text in PowerShell, including output checks and fixes for encoding or formatting problems.
Before you start
This task runs locally in PowerShell and does not require an online conversion service. You need a file or string containing HTML, plus permission to read the source and write the output file. The examples below work with Windows PowerShell 5.1 and PowerShell 7, but the available cmdlets and .NET methods may differ slightly between versions.
Step-by-step instructions
- 1. Get the HTML content. Use Get-Content with the -Raw parameter to read a file as one string: $html = Get-Content -Path .\page.html -Raw. For a web page, use Invoke-WebRequest and take the Content property.
- 2. Strip the tags with a regex replacement. Use $plain = $html -replace '<script.?</script>', ' ' then $plain = $plain -replace '<style.?</style>', ' ' and finally $plain = $plain -replace '<[^>]+>', ' '. This removes script and style blocks first so their content does not appear in the result.
- 3. Decode common HTML entities. Use Add-Type -AssemblyName System.Web and then $plain = [System.Web.HttpUtility]::HtmlDecode($plain). This converts values such as &, < and " into ordinary characters.
- 4. Collapse excess whitespace. Use $plain = $plain -replace '\s+', ' ' and then apply Trim() to remove leading and trailing spaces. If you need visible separation for headings or paragraphs, replace closing block tags with a line break before removing the remaining tags.
- 5. Save the result. Run Set-Content -Path .\page.txt -Value $plain -Encoding UTF8. Choose a different encoding only when your target application requires it.
Check the output
Open the text file and confirm that visible prose remains, scripts and styles are gone, tags no longer appear, and special characters show correctly. If the input contains complex or broken markup, a regex-based conversion may leave extra spaces or merge words that were separated by tags.
Common problems and next steps
- Entities still appear as & or '. Run HtmlDecode after tag removal, not before, and make sure the System.Web assembly loaded correctly.
- Output contains script or style text. Remove script and style regions before removing the rest of the tags.
- Text is one long line. Replace </p>, </div>, </h1> and similar closing block tags with a line break before the generic tag removal step.
- Characters are corrupted. Convert the HTML source to UTF-8 before processing when possible, then write the output as UTF-8 and open it in an editor that supports the same encoding.
- The page is large or uses unusual markup. Regex conversion is fast but not a full HTML parser. For automated processing of many documents, test the command on representative files and keep a copy of the original HTML in case you need another extraction method.