我使用PowerShell腳本生成一些簡單的HTML,並且我想要轉義結果HTML中使用的字符串(因爲它們可以包含一些HTML特定的符號)。在字符串(PowerShell)中轉義HTML特定字符的最佳方法是什麼?
例如:
$a = "something <somthing else>";
應轉換爲以下幾點:
"something <something else>"
是否有任何內置的功能是什麼?
我使用PowerShell腳本生成一些簡單的HTML,並且我想要轉義結果HTML中使用的字符串(因爲它們可以包含一些HTML特定的符號)。在字符串(PowerShell)中轉義HTML特定字符的最佳方法是什麼?
例如:
$a = "something <somthing else>";
應轉換爲以下幾點:
"something <something else>"
是否有任何內置的功能是什麼?
有一個類將在System.Web中做到這一點。
Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::HtmlEncode('something <somthing else>')
你甚至可以走另外一條道路:
[System.Web.HttpUtility]::HtmlDecode('something <something else>')
使用PowerShell 3.0開始,使用[System.Net.WebUtility]
任何常見的四種操作:
[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
是常見的做法以前到.NET 4.0(PowerShell 2.0或更早版本),但需要加載System.Web.dll
:
Add-Type -AssemblyName System.Web
與.NET 4.0(PowerShell的3.0)[System.Web.HttpUtility]::HtmlEnocde
內部調用[System.Net.WebUtility]::HtmlEncode
開始,因此它是有道理的離開了中間人(System.Web.dll
)。
這就是我正在尋找的,謝謝! – Kel 2012-04-10 02:20:18
另一種方法是使用'[System.Security.SecurityElement] :: Escape($ textToEscape)''。存在一些差異;請參閱:https://www.roelvanlisdonk.nl/2009/09/23/you-should-use-system-security-securityelement-escape-in-c-to-escape-special-characters-in-xml-and-沒有系統的web-httputility-的HTMLEncode /。 – JohnLBevan 2017-04-10 14:22:53