What is the best way to escape HTML-specific characters in a string (PowerShell)?

后端 未结 3 1689
情深已故
情深已故 2020-12-05 04:01

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).

3条回答
  •  佛祖请我去吃肉
    2020-12-05 05:03

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

    [System.Net.WebUtility]::HtmlEncode('something ')
    [System.Net.WebUtility]::HtmlDecode('something <somthing else>')
    [System.Net.WebUtility]::UrlEncode('something ')
    [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).

提交回复
热议问题