1

是否可以在 PowerShell 中仅在要传递变量的情况下在 cmdlet 调用上添加参数?

例如

Send-MailMessage -To $recipients (if($copy -ne "") -cc $copy) ....
4

1 回答 1

2

不是你上面写的方式,但你可以splat 参数,用条件构建散列,所以你只有一次调用send-mailmessage. 几个月前我写的一个脚本的例子:

#Set up default/standard/common parameters
$MailParams = @{
"Subject"="This is my subject";
"BodyAsHtml" = $true;
"From" = $MailFrom;
"To" = $MailTo;
"SmtpServer" = $SMTPServer;
};

#On the last day of the month, attach a logfile.
if ((Get-Date).AddDays(1).Day -eq 1) {
$attachment = $LogFilePath;
$ReportContent = "Full log for the the preceding month is attached.<br><br>" + $ReportContent;
$MailParams.Add("Attachments",$attachment);
}

send-mailmessage @MailParms

因此,在您的情况下,它将是:

$MailParams = @{
"Subject"="This is my subject";
"From" = $MailFrom;
"To" = $recipients;
"SmtpServer" = $SMTPServer;
};

if (($copy -ne [string]::empty) -and ($copy -ne $null)) {
$MailParms.Add("CC",$copy);
}

send-mailmessage @MailParms
于 2013-06-20T12:40:55.110 回答