需要以下脚本输出并发送到邮箱

Need the following script to output and send to email

先说吧,我不是很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"}  
}}}

类似这样,但您需要在 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" 

如果您被允许通过 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"