What is the best way to escape HTML-specific characters in a string (PowerShell)?

Kel picture Kel · Apr 10, 2012 · Viewed 32.7k times · Source

I'm generating some simple HTML with PowerShell script, and I would like to escape strings used in result HTML (since they can contain some HTML-specific symbols).

For example:

$a = "something <somthing else>";

should be converted to the following:

"something &lt;something else&gt;"

Is there any built-in function for that?

Answer

Andy Arismendi picture Andy Arismendi · Apr 10, 2012

There's a class that will do this in System.Web.

Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::HtmlEncode('something <somthing else>')

You can even go the other way:

[System.Web.HttpUtility]::HtmlDecode('something &lt;something else&gt;')