如果有要传递的变量,PowerShell中是否可以在cmdlet调用中添加参数?
E.g。
Send-MailMessage -To $recipients (if($copy -ne "") -cc $copy) ....
答案 0 :(得分:2)
不是你上面写的方式,但你可以splat the parameters,用条件构建哈希,这样你只需要调用一次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