Reputation: 7790
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 <something else>"
Is there any built-in function for that?
Upvotes: 42
Views: 50220
Reputation: 69
$SomeEmail = "[email protected]"
$EncodedString = ([uri]::EscapeDataString($SomeEmail))
write-host $EncodedString
Using [uri] ENCODING MAKES IT MUCH EASIER
Upvotes: 4
Reputation: 303
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 <somthing else>')
[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
).
Upvotes: 27
Reputation: 52649
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 <something else>')
Upvotes: 66