Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mandatory and default parameters of a function

Tags:

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!

  Function Send-EMail {       Param (           [Parameter(Mandatory=$true)]  [String]$EmailTo   = "[email protected]", # default           [Parameter(Mandatory=$true)]  [String]$EmailFrom = "[email protected]", #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:

Why this?

What do I have to change so that I am not asked for the already given addresses?

like image 934
gooly Avatar asked Feb 01 '16 10:02

gooly


1 Answers

The Mandatory parameter attribute flag:

[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:

[Parameter(Mandatory=$false)] [string]$EmailTo = "[email protected]", 

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 } 
like image 78
Mathias R. Jessen Avatar answered Oct 20 '22 18:10

Mathias R. Jessen