2017-04-10 128 views
-1

我正在研究一個PowerShell腳本,每次發送多次不同主題和正文的電子郵件。函數多次發送電子郵件

我試圖將Send-MailMessage轉移到一個函數或我可以用來減少代碼行的東西。

$Sender = '[email protected]' 
$text = "<html><body>" 
$text += "<p>Welcome</p>" 

### A cmdlet that would give recipient email address 
$Recipient = (Get-Details -user $user).email 

$smtp = "server.example.com" 
$subject = "welcome email" 

Send-MailMessage -BodyAsHtml $text -from $Sender -SmtpServer $smtp -Priority high -to $Recipient -Subject $subject 

Write-Output "executing commands to capture results" 
Write-Output "" 
### Few Commands executed in this step 
Write-Output "Analyzing results" 
### Few commands executed in this step 

$newtext = "<html><body>" 
$newtext += "Congrats, you are selected" 
$newsubject = "results email" 

Send-MailMessage -BodyAsHtml $newtext -from $Sender -SmtpServer $smtp -Priority high -to $Recipient -Subject $subject 
+0

無論如何,您需要格式化主體,並且將一行「Send-MailMessage」包裝到函數中是不行的。 – Vesper

+0

我刪除了_任何建議,或者我在腳本中可以改進的地方?_因爲這可能使問題太廣泛。如果你真的想要檢查你的腳本,可以考慮在CodeReview.SE上提問 – Matt

回答

0

您可以創建這樣的函數:

Function Send-Email($text,$subject,$recipient) 
{ 
    Send-MailMessage -BodyAsHtml $text -From "[email protected]" 
     -SmtpServer "server.example.com" -Priority High -To $recipient -Subject $subject 
} 

你可以把它想:

Send-Email -text "Hello" -subject "Test" -recipient "[email protected]" 

您可以添加或刪除參數取決於什麼會改變,雖然。假設smtp服務器不會改變,例如,這不需要作爲參數。

0

我試圖將Send-MailMessage轉移到一個函數或我可以用來減少代碼行的東西。

爲一行寫一個函數可以如果選項很多並且永遠不會改變,那麼它會很有用。但是你確實有一個變化。還有另一個PowerShell功能也可以在這裏工作。 Splatting!

$emailParameters = @{ 
    From = $Sender 
    SmtpServer = $smtp 
    Priority = "high" 
    To = $Recipient 
    Subject = $subject 
} 

Send-MailMessage -BodyAsHtml $text @emailParameters 
# ... other code and stuff 
Send-MailMessage -BodyAsHtml $newtext @emailParameters 

現在你仍然只需要在一個地方的變化和代碼可以說是更簡潔。

另一點是,當您一次製作多行字符串時,應該在腳本過程中構建,您始終可以在此處使用字符串。你只有兩條線,但如果你的代碼隨時間演變是一個很好的戰術儘早開始,而不是許多$object += "string"

$text = @" 
<html><body> 
<p>Welcome</p> 
"@ 

注意縮進在結果here-string保留。 "@必須出現在它自己的行中,沒有空白。使用雙引號意味着您仍然可以在其中擴展變量。