Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell parameters with special characters

Tags:

powershell

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)
like image 895
Ola Eldøy Avatar asked Sep 16 '13 09:09

Ola Eldøy


2 Answers

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'"
like image 124
CB. Avatar answered Dec 19 '22 09:12

CB.


simply use ' instead of " to disable expansion

powershell.exe .\sendmail.ps1 -to "[email protected]" -body 'Special character & causing trouble.' -subject 'PowerShell email'

like image 44
Loïc MICHEL Avatar answered Dec 19 '22 08:12

Loïc MICHEL