37

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
  • 29,742
  • 25
  • 114
  • 177
Kel
  • 7,500
  • 3
  • 28
  • 38

3 Answers3

58

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
  • 48,006
  • 16
  • 103
  • 122
  • 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
19

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
  • 193
  • 1
  • 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