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:
What do I have to change so that I am not asked for the already given addresses?
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With