【问题标题】:PowerShell parameters with special characters带有特殊字符的 PowerShell 参数
【发布时间】:2013-09-16 18:06:12
【问题描述】:

我正在编写一个用于发送电子邮件的 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

我尝试使用 ` 转义 &。但该参数仍不会正确包含在脚本中。

我正在寻找一种方法来确保将参数正确传递给脚本,包括特殊字符。我正在考虑使用编码命令,或者可能将参数放在 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)

【问题讨论】:

    标签: powershell


    【解决方案1】:

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

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

    【讨论】:

    • 哇,这似乎真的有效!即使有其他特殊字符。显然,我错过了“呼叫接线员”
    【解决方案2】:

    只需使用' 而不是" 即可禁用扩展

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

    【讨论】:

    • 不幸的是,这不起作用。该字符串缺少终止符:'。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
    • 这在 PS V2 和 PS V3 上运行良好,您的问题可能在您的 sendmail.ps1 中。如果您需要更多帮助,请显示您的脚本。这就是我运行的PS>Send-MailMessage -to "www@yyy.com" -body 'Special character & causing trouble.' -subject 'PowerShell email' -from 'titi@toto.com'
    • 感谢您的意见。我已将脚本包含在我的问题中。
    • 是否有充分的理由通过 COM 使用 Outlook 而不是使用 powershell cmdlet send-mailmessage ??
    • 不幸的是,有一些超出我权限的原因要求通过 COM 使用 Outlook 而不是发送邮件消息。
    猜你喜欢
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多