1
Send-Message `
    -From $emailAuthUser `
    -To $($emailTo -split ',') `
    if($emailCC -ne "NA") { -CC $($emailCC -split ',') } `
    -Subject $emailSubject `
    -Body $emailBody `
    -Attachments $attachments `
    -ReplyTo $($emailReplyTo -split ',') `
    -SmtpServer $emailSmtpServer `
    -Port $emailSmtpPort `
    -Credential $creds `
    -UseSsl

Error: A positional parameter cannot be found that accepts argument 'if'.

Is there an easy way to optionally include a parameter in a "built-in" cmdlet like I am trying to accomplish above? If so, how?

1
  • 3
    You can use Powershell "parameter splatting" to build a hashtable of parameters, and then just add entries for the ones you want to use in any particular invocation. That's pretty easy to do... Commented Nov 22, 2019 at 16:07

2 Answers 2

2

Splatting is the preferred way of performing complex parameter passing. You can store the parameters in a hash table and then add to the hash table using IF blocks. Then splat the hash into your command.

$Params = @{
    From = $emailAuthUser;
    To = $($emailTo -split ',');
    Subject = $emailSubject;
    Body = $emailBody;
    Attachments = $attachments;
    ReplyTo = $($emailReplyTo -split ',');
    SmtpServer = $emailSmtpServer;
    Port = $emailSmtpPort;
    Credential = $creds;
    UseSsl = $True;
}

if($emailCC -ne "NA") { $Params['CC'] = ($emailCC -split ',') }

Send-Message @Params
Sign up to request clarification or add additional context in comments.

Comments

0

I know this is old but just came across this looking for something else. For reference to others you can also slightly modify your existing command.

Send-Message `
    -From $emailAuthUser `
    -To $($emailTo -split ',') `
    -CC $(if($emailCC -ne "NA") { $($emailCC -split ',') }) `
    -Subject $emailSubject `
    -Body $emailBody `
    -Attachments $attachments `
    -ReplyTo $($emailReplyTo -split ',') `
    -SmtpServer $emailSmtpServer `
    -Port $emailSmtpPort `
    -Credential $creds `
    -UseSsl

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.