函数的必需参数和默认参数

时间:2016-02-01 10:04:07

标签: function powershell parameters

我为特殊目的写了一个小的PowerShell send-email-function(错误消息),以便from和to地址始终相同!

  Function Send-EMail {
      Param (
          [Parameter(Mandatory=$true)]  [String]$EmailTo   = "ToAddr@gmx.at", # default
          [Parameter(Mandatory=$true)]  [String]$EmailFrom = "FromAddr@gmail.com", #default
          [Parameter(Mandatory=$true)]  [String]$Subject,
          [Parameter(Mandatory=$true)]  [String]$Body,
          [Parameter(mandatory=$false)] [String]$Attachment,
          [Parameter(mandatory=$true)]  [String]$Password
      )
          $SMTPServer = "smtp.gmail.com"
          $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
          if ($attachment -ne $null) {
              $SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
              $SMTPMessage.Attachments.Add($STMPattachment)
          }
          $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
          $SMTPClient.EnableSsl = $true
          $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password);
          $SMTPClient.Send($SMTPMessage)
          Remove-Variable -Name SMTPMessage
          Remove-Variable -Name SMTPClient
          Remove-Variable -Name Password
          Remove-Variable -Name Body
          Remove-Variable -Name Subject

  } #End Function Send-EMail
  ....
  $subj = "Subject"
  $body = @" Body-Text  "@
  Send-EMail -Subject $subj -Body $body -Password "myPWD" -Attachment $logFile

我现在希望我不必再次指定电子邮件地址,但如果在ISE调试器中逐行运行,则会打开一个小窗口,询问我的EmailTo地址:

Why this?

我需要更改哪些内容,以便不要求我提供已经给定的地址?

1 个答案:

答案 0 :(得分:9)

Mandatory参数属性标志:

[Parameter(Mandatory=$true)]

实际上意味着"调用者必须为此参数提供参数"。

如果您希望参数回退到您在param块中提供的默认值,请将Mandatory标记设置为$false

[Parameter(Mandatory=$false)]
[string]$EmailTo = "to@company.domain",

这可能看起来有点违反直觉,但它允许您检测用户何时没有提供所需的参数:

if(-not($PSBoundParameters.ContainsKey('EmailTo')) -and $EmailTo)
{
    # User relied on default value
}