41

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Kel
  • 7,680
  • 3
  • 29
  • 39

3 Answers3

64

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;')
Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
  • 3
    An alternative is to use `[System.Security.SecurityElement]::Escape($textToEscape)`. Some differences exist; see: https://www.roelvanlisdonk.nl/2009/09/23/you-should-use-system-security-securityelement-escape-in-c-to-escape-special-characters-in-xml-and-not-system-web-httputility-htmlencode/. – JohnLBevan Apr 10 '17 at 14:22
25

Starting with PowerShell 3.0, use [System.Net.WebUtility] for any of the four common operations:

[System.Net.WebUtility]::HtmlEncode('something <somthing else>')
[System.Net.WebUtility]::HtmlDecode('something &lt;somthing else&gt;')
[System.Net.WebUtility]::UrlEncode('something <somthing else>')
[System.Net.WebUtility]::UrlDecode('something+%3Csomthing+else%3E')

[System.Web.HttpUtility]::HtmlEncode is the common approach previous to .NET 4.0 (PowerShell 2.0 or earlier), but would require loading System.Web.dll:

Add-Type -AssemblyName System.Web

Starting with .NET 4.0 (PowerShell 3.0) [System.Web.HttpUtility]::HtmlEnocde internally calls [System.Net.WebUtility]::HtmlEncode, therefore it makes sense to leave out the middle man (System.Web.dll).

Curtis R
  • 253
  • 3
  • 3
3

$SomeEmail = "user@domain.com"

$EncodedString = ([uri]::EscapeDataString($SomeEmail))

write-host $EncodedString

Using [uri] ENCODING MAKES IT MUCH EASIER

  • 2
    Please don't post code and error messages as an image but rather as code-formatted text since none of us can copy, paste and run an image. For more on this, please see why we [**Discourage screenshots of code and/or errors**](https://meta.stackoverflow.com/a/285557/2275490) – Vickel Jul 17 '20 at 01:07
  • URI encoding is different than HTML encoding. URI encoding will encode `<` as `%3C`, not `<` which is what the OP was asking. – JamesQMurphy Feb 08 '23 at 18:53