htmlpowershellhtml-escape-characters

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


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?


Solution

  • 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;')