Sunday, December 15, 2013

Wsus report with powershell


Last Tuesday, someone in our department asked us if it is possible to get a report via email that displays information about failed computers.

By default Windows 2008 R2 does not provide WSUS cmdlets, so we need to load WSUS assemblies from .NET, here is a URL with the method and properties http://msdn.microsoft.com/en-us/library/microsoft.updateservices.administration(v=vs.85).aspx



Here is a code example of what we can do with this assembly:

 $fileid=get-date -uformat "%Y-%m-%d%S"  
 $tmpfile="c:\tmp\mailreport$fileid"  
 [void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")  
 $wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer()  
 $computerScopeID = [Microsoft.UpdateServices.Administration.ComputerTargetGroupId]::AllComputers  
   $wsus.GetComputerTargetGroup($computerScopeID) |  
     ForEach-Object{  
       $_.GetTotalSummaryPerComputerTarget()| foreach-object {  
       $state=$_.Failedcount  
       $compID=$_.ComputerTargetId  
       if ($state -gt 0) {  
       $wsus.GetComputerTargets() | foreach-object {  
       if ($_.id -match $compID )  
       {  
         "`n `r Actualizaciones Fail" + " " + $_.FullDomainName + " " + $_.OSDescription + "`n `r" |Out-File -Append -FilePath $tmpfile  
       }  
       }  
       }  
       }  
     }  
 $report = Get-Content $tmpfile  
 $FromAddress = "Email"  
 $ToAddress = "Email"  
 $MessageSubject = "subject"  
 $MessageBody = "Body  
 $report  
 "  
 $SendingServer = "SMTP01"  
 $SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject, $MessageBody  
 $Attachment = New-Object Net.Mail.Attachment($tmpfile)  
 $SMTPMessage.Attachments.Add($Attachment)  
 $SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer  
 $SMTPClient.Send($SMTPMessage)  
 Remove-item $tmpfile  



No comments:

Post a Comment