需要以下脚本输出并发送到电子邮件

时间:2016-09-19 05:04:06

标签: powershell sendmail email-integration

首先,我不是很懂PS。

我在科技网站的评论中发现了以下脚本,它完成了我想要的所有内容,但是想知道我是否可以将输出生成到电子邮件正文中并发送到指定地址。脚本如下。

$Session = New-Object -ComObject "Microsoft.Update.Session"   
$Searcher = $Session.CreateUpdateSearcher()   
$historyCount = $Searcher.GetTotalHistoryCount()   
$Searcher.QueryHistory(0, $historyCount) | Select-Object Date,    
@{name="Operation"; expression={switch($_.operation){   
    1 {"Installation"}; 2 {"Uninstallation"}; 3 {"Other"}}}},   
@{name="Status"; expression={switch($_.resultcode){ 
    1 {"In Progress"}; 2 {"Succeeded"}; 3 {"Succeeded With Errors"};
    4 {"Failed"}; 5 {"Aborted"}  
}}}

2 个答案:

答案 0 :(得分:0)

这样的东西,但你需要在Send-MailMessage命令中添加正确的信息。

这是send-mailmessage technet,其中包含有关可能参数的更多信息以及不是https://technet.microsoft.com/en-us/library/hh849925.aspx

的内容
$Session = New-Object -ComObject "Microsoft.Update.Session"

$Searcher = $Session.CreateUpdateSearcher()

$historyCount = $Searcher.GetTotalHistoryCount()

$result = $Searcher.QueryHistory(0, $historyCount) | Select-Object Date,@{name="Operation"; expression={switch($_.operation){
   1 {"Installation"}; 
   2 {"Uninstallation"}; 
   3 {"Other"}}}},
   @{name="Status"; expression={switch($_.resultcode){ 
   1 {"In Progress"}; 
   2 {"Succeeded"}; 
   3 {"Succeeded With Errors"};
   4 {"Failed"}; 
   5 {"Aborted"}}}}

$html = "Dear Person, <br/>" 
$html += "Here are the windows update results <br/>"; 
$html += "<table>" 
$html += "<tr>"
$html += "<th>Date of Install</th>"
$html += "<th>Operation</th>"
$html += "<th>Status</th>" 
$html += "</tr>"

foreach ($line in $result) 
{ 
    $date = $line.Date.ToShortDateString()
    $op = $line.Operation
    $stat = $line.Status
    $html += "<tr>"
    $html += "<td> $date </td>" 
    $html += "<td> $op </td>"
    $html += "<td> $stat </td>"
    $html += "</tr>"
}
$html += "</table>"
Send-MailMessage -SmtpServer "smtp.server" -Body $html -BodyAsHtml -From "UpdateSearcher@maildomain.com" -To "Recipient@maildomain.com" -Subject "subject" 

答案 1 :(得分:0)

如果允许您通过SMTP直接发送邮件,则可以将输出放入变量并使用Send-MailMessage

发送
$Session = New-Object -ComObject "Microsoft.Update.Session"
$Searcher = $Session.CreateUpdateSearcher()
$historyCount = $Searcher.GetTotalHistoryCount()
$MailBody = $Searcher.QueryHistory(0, $historyCount) | Select-Object Date,

@{name="Operation"; expression={switch($_.operation){

   1 {"Installation"}; 2 {"Uninstallation"}; 3 {"Other"}}}},

@{name="Status"; expression={switch($_.resultcode){

   1 {"In Progress"}; 2 {"Succeeded"}; 3 {"Succeeded With Errors"};

   4 {"Failed"}; 5 {"Aborted"}

}}}


Send-MailMessage -From "Your Name <your@mail.com>" -To "Receiver1 <Receiver1@mail.com>", "Receiver2 <Receiver2@mail.com>" -Subject "Microsoft Update Session" -Body $MailBody -SmtpServer "your.smtpserver.com"