转义整个字符串变量,该变量可能包含需要转义的字符

时间:2013-09-02 11:53:24

标签: powershell powershell-v3.0

我的PowerShell V3根据一系列问题创建了一个Office 365用户,然后向IT团队发送了一封包含详细信息的电子邮件。问题是:

#Generate-RandomPassword
$xpassword = Create-ComplexPassword -PasswordLength 14 -LowerAlphas 1 -UpperAlphas 1 -Numbers 1 -SpecialCharacters 1
Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::HtmlEncode($xpassword)


Write-Host 'Sending Email' -foregroundcolor yellow
$xbody =  "<head>"
$xbody += "<style>"
$xbody += "p{"
$xbody += "font-family:Verdana;"
$xbody += "font-size:10pt;"
$xbody += "margin-top:0;"
$xbody += "margin-bottom:0;"
$xbody += "}"
$xbody += "</style>"
$xbody += "</head>"
$xbody += "<p>Password: <span style=`"font-family:'Lucida Console',sans serif;font-size:10pt;color:red`">$xpassword</span>"
$xbody += "<p>License: $xk1ore1"
$xbody += "<p>Country: $xcountry"
$xbody += "<p>Town: $xtown"
$xbody += "<p>Status: $xstatus"
$xbody += "<p>Laptop User: $xlaptopuser"
$xbody += "<p>CRM User: $xcrm"
$xbody += "<p>Operations Mailbox Access: $xoperations"
$xbody += "<p>Finance Mailbox Access: $xfinance"
$xbody += "<p>IT Support Mailbox Access: $xitsupport"
$xbody += "<p>Hide from GAL: $xhidefromgal"

Send-O365MailMessage -To itsupport@blah.com -Subject "O365 Account Created" -Body "$xbody" -BodyAsHtml -Credential $cred

变量$ xpassword可能包含需要转义的字符,也可能不包括。当密码包含'&lt;'时例如,我在电子邮件中将其作为一行:

Password: 4*#<(OGyq<="" span="">

我怎样才能满足这个要求?

1 个答案:

答案 0 :(得分:5)

使用.net库:

[System.Web.HttpUtility]::HtmlEncode()

::HtmlDecode读取已编码的字符串。

编辑: 我可以看到你粘贴了你的脚本。而且有一个错误。 方法HtmlEncode()返回System.String,所以改变这个:

[System.Web.HttpUtility]::HtmlEncode($xpassword)

对此:

$xpassword=[System.Web.HttpUtility]::HtmlEncode($xpassword)

否则,您的脚本将只打印编码的字符串,并且$ xpassword保持不变。