I am working on a PowerShell script to send an email, and some of the parameters may contains special characters, such as % and &.
powershell.exe .\sendmail.ps1 -to "[email protected]" -body "Special character & causing trouble." -subject 'PowerShell email'
This gives the following error:
Ampersand not allowed. The & operator is reserved for future use; use "&" to pass ampersand as a string.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : AmpersandNotAllowed
I have tried escaping the & with `. But the parameter will still not be correctly included in the script.
I am looking for a way to make sure the parameters will be correctly passed on to the script, including special characters. I am thinking about using encodedcommand, or perhaps placing the parameters in an xml file.
Any suggestions are most welcome.
Here is the script I am using:
param (
[string]$body = "",
[string]$subject = $(throw "-subject is required."),
[string]$attachment = "",
[string]$to = ""
)
Try
{
$o = [Runtime.InteropServices.Marshal]::GetActiveObject("Outlook.Application")
}
Catch
{
$o = New-Object -com Outlook.Application
}
$mail = $o.CreateItem(0)
$mail.subject = "Auto Build Test"
$mail.body = $body
#for multiple email, use semi-colon ; to separate
$mail.To = $to
$mail.Attachments.Add($attachment)
$mail.Display(0)
Try call the script in this way and let me know:
powershell.exe -command "& .\sendmail.ps1 -to [email protected] -body 'Special character & causing trouble.' -subject 'PowerShell email'"
simply use '
instead of "
to disable expansion
powershell.exe .\sendmail.ps1 -to "[email protected]" -body 'Special character & causing trouble.' -subject 'PowerShell email'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With