1

Question:

I am writing a cmdlet that will accept parameters and send emails. "Cc" is one of the parameters; and is non-mandatory. Today the code shows TWO lines invoking Send-MailMessage (like the following paragraph), but i am sure there is a better way to write it:

if( $cc -eq $null){  
    Send-MailMessage -From $from ...    ## call without -Cc  
} else {  
    Send-MailMessage -From $from ... -Cc $cc...     ## call WITH -Cc  
}  

I would like to avoid branching and writing the line twice.

Or even worse than "twice", writing all the combinations for each optional parameter.

(Of course, the fact that the cmdlet sends email is not important here. The problem will stand for any cmdlet that needs to avoid optional parameters)

What is the best-practice way to do this?

THANK YOU

1 Answer 1

4

Use splatting:

$Params = @{}
if($ShouldUseCc) {
    $Params.Add('Cc', $CcValue)
}
if($ShouldUseBcc) {
    $Params.Add('Bcc', $BccValue)
}
Send-MailMessage -From $from ... @Params
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.