Riccardo
Riccardo

Reputation: 2226

Powershell escaping special characters in HTML string: Ampersand

I am coding a small script used to send emails. It accepts 3 parameters, subject, HTML body & recipient.

HTML body is being read from a file to a string. Troubles come in when HTML code contains special characters, quotes, etc., although HTML is encoded before being passed to the script. Powershell throws this error:

"The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string."

test.ps1

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

$command = ".\sendmail.ps1 –subject 'test email' –body '$encodedBody' -recipient '[email protected]' "

Invoke-Expression $command

Upvotes: 0

Views: 2984

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200393

Invoke-Expression is considered harmful. Do not use it. You don't need it anyway. Just run your commandline as-is (minus the quotes around the variable $encodedBody of course).

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

.\sendmail.ps1 –subject 'test email' –body $encodedBody -recipient '[email protected]'

Upvotes: 1

Related Questions