PowerShell cmdlet 参数列表中的 If 语句
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
错误:找不到接受参数 'if' 的位置参数。
是否有一种 简单 方法可以选择性地将参数包含在 "built-in" cmdlet 中,就像我在上面尝试完成的那样?如果可以,怎么做?
Splatting 是执行复杂参数传递的首选方式。您可以将参数存储在散列 table 中,然后使用 IF 块将其添加到散列 table 中。然后将散列放入您的命令中。
$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
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
错误:找不到接受参数 'if' 的位置参数。
是否有一种 简单 方法可以选择性地将参数包含在 "built-in" cmdlet 中,就像我在上面尝试完成的那样?如果可以,怎么做?
Splatting 是执行复杂参数传递的首选方式。您可以将参数存储在散列 table 中,然后使用 IF 块将其添加到散列 table 中。然后将散列放入您的命令中。
$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