Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 925
Kel Avatar asked Apr 10 '12 02:04

Kel


People also ask

How do you escape special characters in a string in PowerShell?

This means that if you hard code a Distinguished Name in PowerShell, and the string is enclosed in double quotes, any embedded double quotes must be escaped first by a backtick "`", and then by a backslash "\".

What character is the escape character in PowerShell?

The escape character in Powershell is the "`" (backward apostrophe/grave). This can be used to escape quotes and also special characters (e.g., tab is `t).

How do you escape an asterisk in PowerShell?

When you use the –like operator, it supports three wildcards: “*” representing any number of any characters, “?” representing one character, and “[a-z]” for a list of characters. In addition, and this is not widely known, it supports the PowerShell escape character “`” that you can use to escape the wildcards.


1 Answers

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;') 
like image 147
Andy Arismendi Avatar answered Oct 05 '22 23:10

Andy Arismendi