【问题标题】:Powershell escaping special characters in HTML string: AmpersandPowershell转义HTML字符串中的特殊字符:&符号
【发布时间】:2018-12-05 04:57:52
【问题描述】:

我正在编写一个用于发送电子邮件的小脚本。它接受 3 个参数,主题、HTML 正文和收件人。

HTML 正文正在从文件读取到字符串。当 HTML 代码包含特殊字符、引号等时就会出现问题,尽管 HTML 在传递给脚本之前已经过编码。 Powershell 抛出此错误:

"不允许使用与号 (&) 字符。& 运算符保留供将来使用;将 & 号括在双引号 ("&") 中以将其作为字符串的一部分传递。" em>

test.ps1

$theBody = Get-Content ".\welcomeMessageP1.htm" ## HTML !!!
$encodedBody = [System.Net.WebUtility]::HtmlEncode($theBody)

$command = ".\sendmail.ps1 –subject 'test email' –body '$encodedBody' -recipient 'someuser@mydomain.com' "

Invoke-Expression $command

【问题讨论】:

  • 相信用起来会更好。或 & 运行外部脚本而不是 Invoke-Expression。这将避免尝试通过 PowerShell 解释参数
  • Invoke-Expression is considered harmful。不要使用它。只需直接运行您的命令:.\sendmail.ps1 -subject 'test email' -body $encodedBody -recipient 'someuser@mydomain.com'.
  • 再想一想,我认为 HtmlEncode 不足以转义豪华字符。在您的情况下,$encodedBody 中的任何撇号 (') 都将被解释为字符串的结尾。
  • @montonero 仅当他们继续使用Invoke-Expression 时。他们不应该这样做。
  • @montonero:Ansgar 的建议是正确的解决方案,但顺便说一句:至少从 .NET v4.7 / .NET Core 2.1 开始,'(撇号也称为单引号)也被编码:例如[System.Net.WebUtility]::HtmlEncode("a&'b") 产生a&'b。这种行为在早期版本中是否有所不同?

标签: html powershell


【解决方案1】:

Invoke-Expression is considered harmful。不要使用它。反正你也不需要。只需按原样运行命令行(当然要减去变量 $encodedBody 周围的引号)。

$theBody = Get-Content '.\welcomeMessageP1.htm'
$encodedBody = [Net.WebUtility]::HtmlEncode($theBody)

.\sendmail.ps1 –subject 'test email' –body $encodedBody -recipient 'someuser@mydomain.com'

【讨论】:

    猜你喜欢
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2016-01-05
    相关资源
    最近更新 更多