简体   繁体   中英

If statement in PowerShell cmdlet parameter list

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM