有条件地基于空值变量从Send-MailMessage中省略CC参数

Jas*_*ner 2 powershell

我的问题是特定于Send-MailMessagecmdlet的,但我认为这适用于Powershell.

我有一个命令发送一封如下所示的电子邮件:

Send-MailMessage -From $FROM_EMAIL_ADDRESS -To $to -Subject $subject -Body $message -SmtpServer $EMAIL_SERVER
Run Code Online (Sandbox Code Playgroud)

这没什么特别的,定义了此命令中使用的所有变量.

我还有另一个变量$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
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将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
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 8

我会完全使用splatting这个.

$props = @{
    From = $FROM_EMAIL_ADDRESS 
    To= $to 
    Subject = $subject 
    Body = $message 
    SmtpServer = $EMAIL_SERVER 
}

If($cc){$props.Add("CC",$cc)}

Send-MailMessage @props
Run Code Online (Sandbox Code Playgroud)

因此,我们使用我们知道的变量构建一个小哈希表.然后,假设$cc包含有用数据,我们将cc参数附加到哈希表.然后我们splat Send-MailMessage with$props