在字符串 (PowerShell) 中转义 HTML 特定字符的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10082217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:41:28  来源:igfitidea点击:

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

htmlpowershell

提问by Kel

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

我正在使用 PowerShell 脚本生成一些简单的 HTML,我想转义结果 HTML 中使用的字符串(因为它们可以包含一些特定于 HTML 的符号)。

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?

是否有任何内置功能?

回答by Andy Arismendi

There's a class that will do this in System.Web.

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;')

回答by Curtis R

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

从 PowerShell 3.0 开始,[System.Net.WebUtility]用于四种常见操作中的任何一种:

[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]::HtmlEncodeis the common approach previous to .NET 4.0 (PowerShell 2.0 or earlier), but would require loading System.Web.dll:

[System.Web.HttpUtility]::HtmlEncode是 .NET 4.0(PowerShell 2.0 或更早版本)之前的常用方法,但需要加载System.Web.dll

Add-Type -AssemblyName System.Web

Starting with .NET 4.0 (PowerShell 3.0) [System.Web.HttpUtility]::HtmlEnocdeinternally calls [System.Net.WebUtility]::HtmlEncode, therefore it makes sense to leave out the middle man (System.Web.dll).

从 .NET 4.0 (PowerShell 3.0) 开始,[System.Web.HttpUtility]::HtmlEnocde内部调用[System.Net.WebUtility]::HtmlEncode,因此省略中间人 ( System.Web.dll)是有意义的。