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?
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