我的问题仅针对Send-MailMessage
cmdlet,但我认为这适用于Powershell。
我有一个命令发送一封如下所示的电子邮件:
Send-MailMessage -From $FROM_EMAIL_ADDRESS -To $to -Subject $subject -Body $message -SmtpServer $EMAIL_SERVER
这没什么特别的,定义了此命令中使用的所有变量。
我还有另一个变量$cc
,它可能有也可能没有值。如果我进行与上面相同的调用,将-Cc $cc
添加到结尾,当$cc
为空时,我会收到一条错误,指出该命令无法接受此参数的空值。
所以我必须这样做才能克服错误:
if ($cc -eq "")
{
# Email command without the CC parameter.
Send-MailMessage -From $FROM_EMAIL_ADDRESS -To $to -Subject $subject -Body $message -SmtpServer $EMAIL_SERVER
}
else
{
# Email command with the CC parameter.
# This is exactly the same call as above, just the CC param added to the end.
Send-MailMessage -From $FROM_EMAIL_ADDRESS -To $to -Subject $subject -Body $message -SmtpServer $EMAIL_SERVER -Cc $cc
}
有没有办法将Send-MailMessage
操作合并到一个调用中,只有当它不为空时才附加-Cc
?
您可以在批处理脚本中执行此类操作:
# Default to empty param.
$ccParam = ""
# Define the -Cc parameter if it isn't empty.
if ($cc -ne "")
{
$ccParam = "-Cc $cc"
}
# Drop the CC param on the end of the command.
# If it is empty then the CC parameter will not be added (expands to empty value),
# otherwise it will expand to the correct parameter.
Send-MailMessage -To $to [...other params...] $ccParam