Email Reports with PowerShell

Create a report and send it via email is easier than you think and it’s a really useful feature to automate recurring tasks.  This particular example is inspired by another scripting library post about uptime. In fact, I will show you how to create a simple report with all servers bootup time and send it via email in few lines of code or even an oneliner if needed.

​#Requires -RunAsAdministrator 
#Paolo Frigo, https://www.scriptinglibrary.com

# SETTINGS EMAIL REPORT 
$MailRecipient = "Recipient Name <[email protected]>"
$MailSender = "Sender Name <[email protected]>"
$MailServer = "mail.server.com"
$TargetServers = (Get-ADComputer -Filter * | Where-Object {$_.name -like "server-*"  }).Name

$ServerList = @{}
#CHECK SERVER REBOOT TIME
foreach ($Server in $TargetServers ) {
    Try {
        $BootUpTime = (Get-CimInstance -ClassName win32_operatingsystem -ComputerName "$Server" ).LastBootUpTime
    }
    Catch {
        $BootUpTime = "N/A"
    }
    $ServerList.Add($Server, $BootUpTime)
}
#GENERATE EMAIL REPORT
Send-MailMessage -To "$MailRecipient" -From "$MailSender" -Subject "Reboot time of target servers" -Body "$($ServerList|Out-String)" -SmtpServer "$MailServer"
exit 0

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.