简体   繁体   English

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

[英]Mandatory and default parameters of a function

I have written a little PowerShell send-email-function for a special purpose (error-message) so that the from and to addresses are always the same! 我已经为特殊目的编写了一个小的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

I expect now that I don't have to specify again the email address, but if run it line by line in the ISE debugger a little window is opened asking me for the EmailTo address: 我现在希望我不必再次指定电子邮件地址,但如果在ISE调试器中逐行运行,则会打开一个小窗口,询问我的EmailTo地址:

为什么这个?

What do I have to change so that I am not asked for the already given addresses? 我有什么要改变的,以便我不会被要求提供已经给定的地址?

The Mandatory parameter attribute flag: Mandatory参数属性标志:

[Parameter(Mandatory=$true)]

really means "It is mandatory for the caller to supply an argument to this parameter". 实际上意味着“调用者必须为此参数提供参数”。

If you want a parameter to fall back to a default value that you provide in the param block, set the Mandatory flag to $false : 如果您希望参数回退到您在param块中提供的默认值,请将Mandatory标志设置为$false

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

This may seem a little counter-intuitive, but it allows you to detect when a user didn't supply a parameter that is needed: 这可能看起来有点违反直觉,但它允许您检测用户何时未提供所需的参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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