Jason Faulkner
Jason Faulkner

Reputation: 6578

Conditionally omit CC parameter from Send-MailMessage based on a null value variable

My question is specific to Send-MailMessage cmdlet, but I suppose this goes for Powershell in general.

I have a command which sends an email which looks like this:

Send-MailMessage -From $FROM_EMAIL_ADDRESS -To $to -Subject $subject -Body $message -SmtpServer $EMAIL_SERVER

This is nothing special and all the variables used in this command are defined.

I also have another variable $cc which may or may not have a value. If I make the same call as above appending -Cc $cc to the end, when $cc is empty I get an error that the command cannot accept a null value for this parameter.

So I am having to do this to overcome the error:

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
}

Is there a way to consolidate the Send-MailMessage action into a single call which will append -Cc only if it isn't empty?

Something like this which you can do in a batch script:

# 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

Upvotes: 3

Views: 2698

Answers (1)

Matt
Matt

Reputation: 46730

I would totally use splatting for this.

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

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

Send-MailMessage @props

So we build a small hashtable with the variables we know about. Then, assuming the $cc contains useful data, we append the cc parameter to the hashtable. Then we splat Send-MailMessage with $props

Upvotes: 13

Related Questions