带有特殊字符的PowerShell参数

时间:2013-09-16 09:07:56

标签: powershell

我正在使用PowerShell脚本发送电子邮件,而某些参数可能包含特殊字符,例如%和&。

powershell.exe .\sendmail.ps1 -to "user@something.com" -body "Special character & causing trouble." -subject 'PowerShell email'

这会出现以下错误:

Ampersand not allowed. The & operator is reserved for future use; use "&" to pass ampersand as a string.
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : AmpersandNotAllowed

我试过逃避&与`。但该参数仍未正确包含在脚本中。

我正在寻找一种方法来确保将参数正确传递给脚本,包括特殊字符。我正在考虑使用encodedcommand,或者可能将参数放在xml文件中。

欢迎任何建议。

这是我正在使用的脚本:

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)

2 个答案:

答案 0 :(得分:9)

尝试以这种方式调用脚本并告诉我:

powershell.exe -command "& .\sendmail.ps1 -to user@something.com -body 'Special character & causing trouble.' -subject 'PowerShell email'"

答案 1 :(得分:3)

只需使用'代替"即可停用展开

powershell.exe .\sendmail.ps1 -to "user@something.com" -body 'Special character & causing trouble.' -subject 'PowerShell email'