How to Build a Daily Systems Report Email in OpenManage Essentials This Dell technical white paper provides step-by-step instructions to build a daily HTML systems report in OpenManage Essentials. BBenjamin Villanueva Dell Enterprise Product Group How to build a daily systems report email on OpenManage Essentials This document is for informational purposes only and may contain typographical errors and technical inaccuracies. The content is provided as is, without express or implied warranties of any kind. © 2012 Dell Inc. All rights reserved. Dell and its affiliates cannot be responsible for errors or omissions in typography or photography. Dell, the Dell logo, and PowerEdge are trademarks of Dell Inc. Intel and Xeon are registered trademarks of Intel Corporation in the U.S. and other countries. Microsoft, Windows, and Windows Server are either trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Other trademarks and trade names may be used in this document to refer to either the entities claiming the marks and names or their products. Dell disclaims proprietary interest in the marks and names of others. October 2012| Rev 1.0 ii How to build a daily systems report email on OpenManage Essentials Contents Executive summary ................................................................................................... 4 Introduction ........................................................................................................... 4 Prerequisites .......................................................................................................... 4 Installing OpenManage Essentials ................................................................................. 4 Windows PowerShell requirements ............................................................................... 5 Environment discovery and inventory ............................................................................ 5 Script requirements ................................................................................................. 5 Items reported in the daily systems report ..................................................................... 5 Systems report output .............................................................................................. 6 Daily systems report script .......................................................................................... 7 Complete script ...................................................................................................... 17 Configuring the script on a daily basis as a remote task ...................................................... 17 Within OpenManage Essentials: .................................................................................. 17 Creating a servers.txt file: ...................................................................................... 17 Creating a daily HTML report task ............................................................................. 19 Conclusion ............................................................................................................ 21 Learn more .......................................................................................................... 21 Appendix A .......................................................................................................... 22 iii How to build a daily systems report email on OpenManage Essentials Executive summary OpenManage Essentials (OME) is a systems management console that provides simple, basic Dell hardware management and is available as a free download. OME is an essential tool for administrators to assist in managing their environment. Some of the benefits of using OME in your environment include: Discovery, inventory, and monitoring Dell servers Create and schedule remote tasks on Dell Servers Leverage PowerShell and other scripting languages This white paper demonstrates the prerequisites to build a daily systems report email with PowerShell to take advantage of these benefits. Introduction OpenManage Essentials provides a central point of access to monitor and manage systems on a local area network (LAN). By allowing a comprehensive view across the enterprise, Essentials increases system uptime, reduces repetitive tasks, and prevents interruption in critical business operations. As datacenters become more automated, it is necessary to create daily system reports to proactively detect and diagnose issues before they impact business operations. The script provided within this whitepaper is configured to perform other health checks that are more common within a systems administrator’s day-to-day job. The script is also build in a modular layout allowing you to enable or disable certain functions within the systems report. Prerequisites Installing OpenManage Essentials Download the latest version of OpenManage Essentials package from support.dell.com Web site. 1. Browse to the server on which you want to install OpenManage Essentials. 2. Click on Drivers and Download tab. 3. Expand the Systems Management. 4. Find the OpenManage Essentials application and download the file. You can find detailed steps for installing OME at the following location: http://en.community.dell.com/techcenter/extras/m/white_papers/19998614.aspx 4 How to build a daily systems report email on OpenManage Essentials Windows PowerShell requirements Set up OpenManage Essentials to run the PowerShell script contained in this whitepaper requires the “Execution Policy” to be set to “Remote Signed”. 1. To verify the current execution policy, type the following command from the Windows PowerShell command prompt: Get-ExecutionPolicy 2. To change the current execution policy, type: Set-ExecutionPolicy RemoteSigned 3. When prompted to accept the changes press enter or type “Y” and press Enter. Once the execution policy is set to Remote Signed, OpenManage Essentials runs the script and produces and emails the daily systems report. Environment discovery and inventory A fundamental element of any organization’s device management is the discovery and inventory of all devices in your network. Discovery needs to be non-invasive, easy to administer, efficient, thorough, accurate, broad in scope, and responsive to network changes. Discovery is a process for identifying all Dell hardware devices in your network, such as Dell PowerEdge servers and Dell out-of-band devices (iDRAC). To understand and configure OME and to discover and inventory your environment, go to: http://en.community.dell.com/techcenter/extras/m/white_papers/19998626.aspx After discovery and inventory of your environment OpenManage Essentials targets a specific group of servers to build the daily systems report email. Script requirements The following items are what the script requires to properly generate the report.: All servers need to be part of Active Directory Credentials running script needs to have administrative privileges on servers Domain Name System (DNS) servers configured to have Pointer Records ( PTR ) of the servers Items reported in the daily systems report The following items are what the script reports for each server: System Report i. System Uptime ii. Computer Name iii. Computer Domain iv. Manufacturer v. Model 5 How to build a daily systems report email on OpenManage Essentials vi. Operating System vii. Total RAM (GB) viii. Free RAM (GB) ix. Percent free RAM Disk Report i. All drives with % free space below thresholds set Processes Report i. Top 10 highest working set memory usage processes Services Report i. Any service set to startup automatically but that is not started System and Application Event Report i. The last few system and application event logs that were either warning or critical Systems report output Each section of the report generates an HTML portion that is appended to the final systems report file. Figure 1. Example of the top portion of the report. The HTML file created is a fully validated XHTML 1.0 Transitional. This means that the resource in question identified itself as "XHTML 1.0 Transitional" and that we successfully performed a formal validation of it. 6 How to build a daily systems report email on OpenManage Essentials Using the W3C Markup Validation Service at http://validator.w3.org we can verify it has passed validation. Figure 2. Passing validation. Daily systems report script At the end of the document, is the complete script with comments that you can customize for your environment. Throughout the white paper, a smaller section of the report is shown to help emphasis specific areas of the script. To keep things as customizable as possible, the reporting script is built in a modular fashion where each section of information relies on a PowerShell function that retrieves or builds the information from the servers. To start with, we have defined a couple of variables and parameters that must be customized for each environment such as: Path where to save the HTML report Disk space free percent warning threshold Disk space free percent critical threshold 7 How to build a daily systems report email on OpenManage Essentials Number of processes to fetch that are using the most amount of memory Number of systems and application event logs to fetch that are either a warning or critical type Users who will receive a daily HTML report of the servers Mail Server that will be used to send the email out The main section of our report is detailed below: # Daily HTML Email Report from OpenManage Essentials Function Get-DailyHTMLReport { $Path = "c:\tmp" $OutputFile= "DailyReport_$(get-date -format ddMMyyyy).html" # Name of the file that gets emailed out $list = $args[0] #This accepts the argument you add to your scheduled task in OME or list.txt $computerList = Get-Content $list # grab the names of the servers/computers from file #Set warning and critical thresholds below in percent for disk report $FreePercentWarningThreshold=30 $FreePercentCriticalThreshold=10 #Number of proccess to fetch that are using the most amount of memory $ProccessNumToFetch = 10 #Number of events to gather from system and application logs that are either warning or critical $EventNum = 5 #Email settings for report $users = "[email protected]" #List of users to email your report to (separated by comma) $fromemail = "[email protected]" $server = "smtp.mycompany.com" #SMTP server to use for sending out email Once we have defined these variables and arguments, let’s look at each function once at a time. Before running through the script, we test to make sure the computer is up and that you have proper credentials to gather the information from the remote host, by using the following code: #Test to make sure computer is up and that you are using the proper credentials if ((Test-Connection -ComputerName $computer -Quiet -Count 1) -and (Test-Path \\$Computer\admin`$)) After verifying the computer is up and we have proper access, we can translate the IP of the server into a fully qualified domain name for our report header using the following code: $IP = [System.Net.Dns]::GetHostEntry($computer).AddressList | %{$_.IPAddressToString} $IP | %{$HostName = [System.Net.Dns]::GetHostEntry($_).HostName} 8 How to build a daily systems report email on OpenManage Essentials Create a header for each server we are processing and add it to our report: $compHeader = @" <table> <tr> <td colspan="6"><h2>Report for: $hostname</h2></td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $compHeader Run through each function and add it to our report: # Run the inventory report InventoryReport # Run the disk report usage DiskReport # Run the top processes report ProcessReport # Run the services report ServiceReport # Run the System Event Log Report SystemLogReport # Run the Application Event Log Report AppLogReport Make sure that we have closed out all open tags within the report: Add-Content "$Path\$OutputFile" "</div></div></body></html>" Finally, email the report and add it as an attachment as well: # Email out report and add HTML file as an attachment $HTMLmessage = get-content $Path\$OutputFile send-mailmessage -from $fromemail -to $users -subject "Daily Systems Report" -BodyAsHTML -body "$HTMLmessage" -attachment $Path\$OutputFile -priority Normal -smtpServer $server We use CSS to make the report more readable and configured the report to be resizable based on the browser width or the screen width to preserve the aspect ratio. CSS also enables the report to be viewed on any smartphone without the need to scroll left or right. To accomplish this, we need to create an HTML header that goes into our report and defines the CSS we want to use. You can customize each section of the CSS for your needs: Function writeHtmlHeader { $date = (get-date -Format F) $header = @" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 9 How to build a daily systems report email on OpenManage Essentials <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Daily Reports</title> <style type="text/css"> <!-body { font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif; background: #FFFFFF; margin: 0; padding: 0; color: #000; } .container { width: 100%; margin: 0 auto; } h1 { font-size: 18px; } h2 { color: #FFF; padding: 0px; margin: 0px; font-size: 14px; background-color: #006400; } h3 { color: #FFF; padding: 0px; margin: 0px; font-size: 14px; background-color: #191970; } h4 { color: #348017; padding: 0px; margin: 0px; font-size: 10px; font-style: italic; } .header { text-align: center; } .container table { width: 100%; font-family: Verdana, Geneva, sans-serif; font-size: 12px; font-style: normal; font-weight: bold; font-variant: normal; text-align: center; border: 2px solid black; padding: 0px; margin: 0px; } td { 10 How to build a daily systems report email on OpenManage Essentials font-weight: normal; border: 1px solid grey; } th { font-weight: bold; border: 1px solid grey; text-align: center; } --> </style></head> <body> <div class="container"> <div class="header"> <h1>OpenManage Daily Reports</h1> <h1>$date</h1> </div> <div class="content"> "@ Add-Content "$Path\$OutputFile" $header For our disk space function with the defined thresholds above, we colorized them to determine at-aglance the status of which disk is in a warning and critical state: Function WriteDiskInfo ( [string]$fileName, [string]$devId, [string]$volName, [double]$freeSpace, [double]$totalSpace ) { $greenColor = "#638B38" $yellowColor = "#F5BD22" $redColor = "#C1281C" We then performed some basic math calculations on each disk to determine what state it is in: $totalSpace=[math]::Round(($totalSpace/1GB),2) $freeSpace=[Math]::Round(($freeSpace/1GB),2) $usedSpace = $totalSpace - $freeSpace $usedSpace=[Math]::Round($usedSpace,2) $freePercent = ($freeSpace/$totalSpace)*100 $freePercent = [Math]::Round($freePercent,0) From our math calculations, we determined what color the disk should be reported on by using “if” statements and added it to the report: if ($freePercent -gt $FreePercentWarningThreshold) { $color = $greenColor 11 How to build a daily systems report email on OpenManage Essentials $dataRow = @" <tr> <td>$devid</td> <td>$volName</td> <td>$totalSpace</td> <td>$usedSpace</td> <td>$freeSpace</td> <td style="background-color: #638B38;">$freePercent</td> </tr> "@ Add-Content $fileName $dataRow } elseif ($freePercent -le $FreePercentCriticalThreshold) { $color = $redColor $dataRow = @" <tr> <td>$devid</td> <td>$volName</td> <td>$totalSpace</td> <td>$usedSpace</td> <td>$freeSpace</td> <td style="background-color: #C1281C;">$freePercent</td> </tr> "@ Add-Content $fileName $dataRow } else { $color = $yellowColor $dataRow = @" <tr> <td>$devid</td> <td>$volName</td> <td>$totalSpace</td> <td>$usedSpace</td> <td>$freeSpace</td> <td style="background-color: #F5BD22;">$freePercent</td> </tr> "@ Add-Content $fileName $dataRow } } We finished the disk report by assembling all the pieces together using the following function: Function DiskReport { $DiskReportHeader = @" <table> <tr> <td colspan="6"><h3>Disk Report</h3> <h4>Drive(s) listed below have less than $thresholdspace % free space. Disk within the thresholds specified are colored to identify them easily</h4> </td> </tr> 12 How to build a daily systems report email on OpenManage Essentials <tr> <th>Drive</th> <th>Drive Label</th> <th>Total Capacity (GB)</th> <th>Used Capacity (GB) </th> <th>Free Space (GB) </th> <th>Freespace %</th> </tr> "@ Add-Content "$Path\$OutputFile" $DiskReportHeader $disks = Get-WmiObject win32_logicaldisk -ComputerName $computer | Where-Object {$_.drivetype -eq 3} foreach ($item in $disks) { WriteDiskInfo "$Path\$OutputFile" $item.DeviceID $item.VolumeName $item.FreeSpace $item.Size } Add-Content "$Path\$OutputFile" "</table><p></p>" } For our report, we also wanted to know how long our server has been up and running: Function Get-HostUptime { Write-Host $Computer $Uptime = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer $LastBootUpTime = $Uptime.ConvertToDateTime($Uptime.LastBootUpTime) $Time = (Get-Date) - $LastBootUpTime Return '{0:00} Days, {1:00} Hours, {2:00} Minutes, {3:00} Seconds' -f $Time.Days, $Time.Hours, $Time.Minutes, $Time.Seconds } At the start of our report we pulled in some basic inventory from the server and added it to our report: Function InventoryReport { $OS = (Get-WmiObject Win32_OperatingSystem -computername $computer).caption $SystemInfo = Get-WmiObject -Class Win32_OperatingSystem -computername $computer | Select-Object Name, TotalVisibleMemorySize, FreePhysicalMemory $ModelInfo = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer | Select-Object Manufacturer, Model,DNSHostName,Domain $TotalRAM = $SystemInfo.TotalVisibleMemorySize/1MB $FreeRAM = $SystemInfo.FreePhysicalMemory/1MB $UsedRAM = $TotalRAM - $FreeRAM $RAMPercentFree = ($FreeRAM / $TotalRAM) * 100 $TotalRAM = [Math]::Round($TotalRAM, 2) $FreeRAM = [Math]::Round($FreeRAM, 2) $UsedRAM = [Math]::Round($UsedRAM, 2) $RAMPercentFree = [Math]::Round($RAMPercentFree, 2) $Make = $ModelInfo.model $Made = $ModelInfo.manufacturer $Name = $ModelInfo.DNSHostName $Domain = $ModelInfo.Domain $SystemUptime = Get-HostUptime -ComputerName $computer $InventoryReportHeader = @" 13 How to build a daily systems report email on OpenManage Essentials <table> <tr> <td colspan="6"><h3>Inventory Report</h3> <h4>This provides a basic overview of the system and some key statistics.</h4> </td> </tr> <tr> <th>System Uptime</th> <td>$SystemUptime</td> </tr> <tr> <th>Computer Name</th> <td>$Name</td> </tr> <tr> <th>Computer Domain</th> <td>$Domain</td> </tr> <tr> <th>Manufacturer</th> <td>$Made</td> </tr> <tr> <th>Model</th> <td>$Make</td> </tr> <tr> <th>Operating System</th> <td>$OS</td> </tr> <tr> <th>Total RAM (GB)</th> <td>$TotalRAM</td> </tr> <tr> <th>Free RAM (GB)</th> <td>$FreeRAM</td> </tr> <tr> <th>Percent free RAM</th> <td>$RAMPercentFree</td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $InventoryReportHeader } For the number of processes we defined, we calculated which ones are using the highest amounts of memory. Function ProcessReport { $ProcessReportHeader = @" <table> 14 How to build a daily systems report email on OpenManage Essentials <tr> <td colspan="6"><h3>Processes Report</h3> <h4>The following $ProccessNumToFetch processes are those consuming the highest amount of Working Set (WS) Memory (bytes) on $computer</h4></td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $ProcessReportHeader $TopProcesses = (Get-process -ComputerName $computer | select-object ws,name | sort-object –property WS -Descending | select-object –First $ProccessNumToFetch | convertto-html -Fragment) | Add-Content "$Path\$OutputFile" Add-Content "$Path\$OutputFile" "<p></p>" } For each service running on the server, we determined which ones are set to automatically start but are stopped, this might mean the application crashed or was unable to start. Function ServiceReport { $ServiceReportHeader = @" <table> <tr> <td colspan="6"><h3>Services Report</h3> <h4>The following services are those which are set to Automatic startup type, yet are currently not running on $computer</h4></td> </tr> </table><p></p> "@ $Services = (Get-WmiObject -Class Win32_Service -ComputerName $computer | Select-Object DisplayName,Name,StartMode,State | Where-Object {$_.StartMode eq "Auto" -and $_.State -eq "Stopped"}) If ($Services -ne $null) { Add-Content "$Path\$OutputFile" $ServiceReportHeader $StopServices = (Get-WmiObject -Class Win32_Service -ComputerName $computer | Select-Object DisplayName,Name,StartMode,State | WhereObject {$_.StartMode -eq "Auto" -and $_.State -eq "Stopped"} | ConvertTo-Html -Fragment) -replace "<table>",'<table>' | Add-Content "$Path\$OutputFile" Add-Content "$Path\$OutputFile" "<p></p>" } } To finish our report we are going to look at the system and application event logs and add them to our report. #Assemble System Event Log Report Function SystemLogReport { $SysReportHeader = @" 15 How to build a daily systems report email on OpenManage Essentials <table> <tr> <td colspan="6"><h3>System Event Report</h3> <h4>The following is a list of the last $EventNum <b>System log</b> events that had an Event Type of either Warning or Error on $computer</h4></td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $SysReportHeader $SystemEvents = (Get-EventLog -ComputerName $computer -LogName System EntryType Error,Warning -Newest $EventNum | Select-Object Message,Source,EntryType,TimeGenerated | ConvertTo-Html -Fragment) -replace "<table>",'<table style="text-align: left" >' | Add-Content "$Path\$OutputFile" Add-Content "$Path\$OutputFile" "<p></p>" } #Assemble Application Event Log Report Function AppLogReport { $AppReportHeader = @" <table> <tr> <td colspan="6"><h3>Application Event Report</h3> <h4>The following is a list of the last $EventNum <b>Application log</b> events that had an Event Type of either Warning or Error on $computer</h4></td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $AppReportHeader $ApplicationEvents = (Get-EventLog -ComputerName $computer -LogName Application -EntryType Error,Warning -Newest $EventNum | Select-Object Message,Source,EntryType,TimeGenerated | ConvertTo-Html -Fragment) -replace "<table>",'<table style="text-align: left">' | Add-Content "$Path\$OutputFile" Add-Content "$Path\$OutputFile" "<p></p>" } Finally we called out main report script using: # Run Main Report Get-DailyHTMLReport $args[0] 16 How to build a daily systems report email on OpenManage Essentials Complete script Please see Appendix A for the full script with comments for you to customize for your environment: Configuring the script on a daily basis as a remote task First create a directory called Daily Reports. Use this directory to store your PowerShell scripts and a copy of the daily systems report for the day. There are two ways you can configure this script to run, standalone or within OpenManage Essentials. Within OpenManage Essentials: The script requires a list of servers to run against. Obtain the list by using one of the following: a) A file that contains the list of IP addresses for each server, each on its own line. b) Create a one-time task of creating a file with the IP address of the servers within OME. Note: Option “b” only provides the IP address the server was discovered on. If the server has multiple IP addresses assigned, it only provides the last IP used to discover and inventory the server. The PowerShell script for the task in option “b” to create this list is: $server = $args[0] $OutputFile = "servers.txt" $Path = "c:\dailyreport" New-Item -ItemType File -Name $OutputFile -Path $Path | Out-Null Write-Output $server | Out-File -FilePath "$path\$Outputfile" -Append -NoClobber Save this script as “servers.ps1” into your daily systems reports directory. Creating a servers.txt file: 1. Open up the OpenManage Essentials console, and navigate to Manage -> Remote Tasks. 2. Click Create Command Line Task and select Generic Command. 3. Name the task Server List. 4. In the command box type: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe 5. In the arguments box type: -noprofile -file "c:\dailyreport\servers.ps1" $IP The command line task should look as follows: 17 How to build a daily systems report email on OpenManage Essentials Figure 3. Example screenshot of the task. 6. Click Next. 7. On the Task Target tab, select the servers you will be running the report on. 8. Click Next. 9. On the Schedule and Credentials tab, select Run Now and enter the appropriate credentials. 10. Click Finish. Once the task completes, this generates a servers.txt file in the daily reports directory. 18 How to build a daily systems report email on OpenManage Essentials Creating a daily HTML report task Once we have the servers.txt file required for the script, we can then create our daily systems report by following these steps: 1. Open up the OpenManage Essentials console; navigate to Manage -> Remote Tasks. 2. Click Create Command Line Task and select Generic Command. 3. Name the task Daily HTML Report. 4. In the command box type: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe. 5. In the arguments box type: -noprofile -file c:\dailyreport\dailyreport-OME.ps1 c:\dailyreport\servers.txt The command line task should look as follows: 19 How to build a daily systems report email on OpenManage Essentials Figure 4. Example screen shot of the command-line task. 6. On the Schedule and Credentials tab, select Set Schedule. 7. Select Periodic. 8. Choose Daily. 9. Enter the start time for the report to run, for example: 12:00am. 10. Enter the appropriate credentials for the task to run. 11. Click Finish. 20 How to build a daily systems report email on OpenManage Essentials Each server that is specified in the servers.txt file has its own entry into the daily report. By completing this setup and configuration you now have a daily systems report emailed to you on a regular basis to facilitate your day-to-day job. Conclusion Dell OpenManage Essentials provides a single, easy-to-use, one-to-many, customizable console to manage Dell hardware, including: servers, storage, and network switches, as well as other existing Dell systems in your environment. OpenManage Essentials helps simplify hardware management and streamlines IT Operations by automating the basic repetitive hardware management tasks such as discovering and inventorying servers, storage, and network switches, monitoring their health status, and sending email alerts for unattended monitoring. Learn more Visit www.dell.com/ome or www.delltechcenter.com/ome for more information on Dell OpenManage Essentials. 21 How to build a daily systems report email on OpenManage Essentials Appendix A Copy and paste the script below and name it dailyreport-OME.ps1 # Daily HTML Email Report from OpenManage Essentials # This report can be ran either as a standalone or within OME # It will gather basic inventory, provide a disk space report # processes report, service report, system and application # event log. # # This script will generate a valid XHTML 1.0 Transitional HTML file # that is emailed out to users specified below. # # Check validation at http://validator.w3.org. Results from validator: # This document was successfully checked as XHTML 1.0 Transitional! # # Example usage as standalone, from PowerShell command window type: # .\dailyreport-OME.ps1 .\servers.txt # where servers.txt is a file containing a list of Server names or IP's to run this against. # # Example usage using OME is to create a generic command line task and run this script against # the servers.txt task that creates the txt file that is used for a scheduled tasks. Function Get-DailyHTMLReport { $Path = "c:\tmp" $OutputFile= "DailyReport_$(get-date -format ddMMyyyy).html" # Name of the file that gets emailed out $list = $args[0] #This accepts the argument you add to your scheduled task in OME or list.txt $computerList = Get-Content $list # grab the namesof the servers/computers from file #Set warning and critical thresholds below in percent for disk report $FreePercentWarningThreshold=30 $FreePercentCriticalThreshold=10 #Number of proccess to fetch that are using the most amount of memory $ProccessNumToFetch = 10 #Number of events to gather from system and application logs that are either warning or critical $EventNum = 3 #Email settings for report $users = "[email protected]" #List of users to email your report to (separated by comma) $fromemail = "[email protected]" $server = "smtp.mycompany.com" #SMTP server to use for sending out email Write-Host "Starting to Generate HTML Daily Email Report...." #Create a new report file to be emailed out New-Item -ItemType File -Name $OutputFile -Path $Path -Force | Out-Null #Write the HTML header information to file writeHtmlHeader "$Path\$OutputFile" 22 How to build a daily systems report email on OpenManage Essentials #Process each server and run through script foreach ($computer in $ComputerList) { $ErrorActionPreference = "silentlycontinue" #Test to make sure computer is up and that you are using the proper credentials if ((Test-Connection -ComputerName $computer -Quiet -Count 1) -and (Test-Path \\$Computer\admin`$ ) ) { #Convert IP into an FQDN name for our report write-host "$computer - UP" -ForegroundColor Green $IP = [System.Net.Dns]::GetHostEntry($computer).AddressList | %{$_.IPAddressToString} $IP | %{$HostName = [System.Net.Dns]::GetHostEntry($_).HostName} If ($IP) { Write-Host "IP is $IP" Write-Host "Hostname is $hostname" $wmi = (gwmi -computer $hostname win32_service) If ($wmi) { #Create a header for each server we are processing $compHeader = @" <table> <tr> <td colspan="6"><h2>Report for: $hostname</h2></td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $compHeader # Run the inventory report InventoryReport # Run the disk report usage DiskReport # Run the top processes report ProcessReport # Run the services report ServiceReport # Run the System Event Log Report SystemLogReport # Run the Application Event Log Report AppLogReport } else { Write-Host "Unable to access to WMI, please check the user has admin access to server" } } else 23 How to build a daily systems report email on OpenManage Essentials { write-host "No Hostname found make sure you have DNS PTR records for your servers" } } else { Write-Host "$computer Wrong Credentials, Not Responding or Not a Windows Server" -ForegroundColor Red } } # Close out all open HTML tags Add-Content "$Path\$OutputFile" "</div></div></body></html>" # Finish up Report Write-Host "Daily HTML Report File Path is: $Path\$OutputFile" ForegroundColor Green # Email out report and add HTML file as an attachment $HTMLmessage = get-content $Path\$OutputFile send-mailmessage -from $fromemail -to $users -subject "Daily Systems Report" -BodyAsHTML -body "$HTMLmessage" -attachment $Path\$OutputFile priority Normal -smtpServer $server } # Write HTML Header information to our Report # Use CSS to make report more readable Function writeHtmlHeader { $date = (get-date -Format F) $header = @" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Daily Reports</title> <style type="text/css"> <!-body { font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif; background: #FFFFFF; margin: 0; padding: 0; color: #000; } .container { width: 100%; margin: 0 auto; } h1 { font-size: 18px; } h2 { color: #FFF; padding: 0px; margin: 0px; font-size: 14px; background-color: #006400; } 24 How to build a daily systems report email on OpenManage Essentials h3 { color: #FFF; padding: 0px; margin: 0px; font-size: 14px; background-color: #191970; } h4 { color: #348017; padding: 0px; margin: 0px; font-size: 10px; font-style: italic; } .header { text-align: center; } .container table { width: 100%; font-family: Verdana, Geneva, sans-serif; font-size: 12px; font-style: normal; font-weight: bold; font-variant: normal; text-align: center; border: 2px solid black; padding: 0px; margin: 0px; } td { font-weight: normal; border: 1px solid grey; } th { font-weight: bold; border: 1px solid grey; text-align: center; } --> </style></head> <body> <div class="container"> <div class="header"> <h1>OpenManage Daily Reports</h1> <h1>$date</h1> </div> <div class="content"> "@ Add-Content "$Path\$OutputFile" $header } # Go through all disks on the server and color code the ones that are # in the thresholds specified above for warning and critical Function WriteDiskInfo ( [string]$fileName, [string]$devId, [string]$volName, 25 How to build a daily systems report email on OpenManage Essentials [double]$freeSpace, [double]$totalSpace ) { $greenColor = "#638B38" $yellowColor = "#F5BD22" $redColor = "#C1281C" $totalSpace=[math]::Round(($totalSpace/1GB),2) $freeSpace=[Math]::Round(($freeSpace/1GB),2) $usedSpace = $totalSpace - $freeSpace $usedSpace=[Math]::Round($usedSpace,2) $freePercent = ($freeSpace/$totalSpace)*100 $freePercent = [Math]::Round($freePercent,0) if ($freePercent -gt $FreePercentWarningThreshold) { $color = $greenColor $dataRow = @" <tr> <td>$devid</td> <td>$volName</td> <td>$totalSpace</td> <td>$usedSpace</td> <td>$freeSpace</td> <td style="background-color: #638B38;">$freePercent</td> </tr> "@ Add-Content $fileName $dataRow } elseif ($freePercent -le $FreePercentCriticalThreshold) { $color = $redColor $dataRow = @" <tr> <td>$devid</td> <td>$volName</td> <td>$totalSpace</td> <td>$usedSpace</td> <td>$freeSpace</td> <td style="background-color: #C1281C;">$freePercent</td> </tr> "@ Add-Content $fileName $dataRow } else { $color = $yellowColor $dataRow = @" <tr> <td>$devid</td> <td>$volName</td> <td>$totalSpace</td> <td>$usedSpace</td> <td>$freeSpace</td> <td style="background-color: #F5BD22;">$freePercent</td> </tr> "@ 26 How to build a daily systems report email on OpenManage Essentials Add-Content $fileName $dataRow } } # Provide the time the server has been up Function Get-HostUptime { Write-Host $Computer $Uptime = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer $LastBootUpTime = $Uptime.ConvertToDateTime($Uptime.LastBootUpTime) $Time = (Get-Date) - $LastBootUpTime Return '{0:00} Days, {1:00} Hours, {2:00} Minutes, {3:00} Seconds' -f $Time.Days, $Time.Hours, $Time.Minutes, $Time.Seconds } #Gather basic inventory from server Function InventoryReport { $OS = (Get-WmiObject Win32_OperatingSystem -computername $computer).caption $SystemInfo = Get-WmiObject -Class Win32_OperatingSystem -computername $computer | Select-Object Name, TotalVisibleMemorySize, FreePhysicalMemory $ModelInfo = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $computer | Select-Object Manufacturer, Model,DNSHostName,Domain $TotalRAM = $SystemInfo.TotalVisibleMemorySize/1MB $FreeRAM = $SystemInfo.FreePhysicalMemory/1MB $UsedRAM = $TotalRAM - $FreeRAM $RAMPercentFree = ($FreeRAM / $TotalRAM) * 100 $TotalRAM = [Math]::Round($TotalRAM, 2) $FreeRAM = [Math]::Round($FreeRAM, 2) $UsedRAM = [Math]::Round($UsedRAM, 2) $RAMPercentFree = [Math]::Round($RAMPercentFree, 2) $Make = $ModelInfo.model $Made = $ModelInfo.manufacturer $Name = $ModelInfo.DNSHostName $Domain = $ModelInfo.Domain $SystemUptime = Get-HostUptime -ComputerName $computer $InventoryReportHeader = @" <table> <tr> <td colspan="6"><h3>Inventory Report</h3> <h4>This provides a basic overview of the system and some key statistics.</h4> </td> </tr> <tr> <th>System Uptime</th> <td>$SystemUptime</td> </tr> <tr> <th>Computer Name</th> <td>$Name</td> </tr> <tr> <th>Computer Domain</th> <td>$Domain</td> </tr> <tr> 27 How to build a daily systems report email on OpenManage Essentials <th>Manufacturer</th> <td>$Made</td> </tr> <tr> <th>Model</th> <td>$Make</td> </tr> <tr> <th>Operating System</th> <td>$OS</td> </tr> <tr> <th>Total RAM (GB)</th> <td>$TotalRAM</td> </tr> <tr> <th>Free RAM (GB)</th> <td>$FreeRAM</td> </tr> <tr> <th>Percent free RAM</th> <td>$RAMPercentFree</td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $InventoryReportHeader } # Assemble the disk report Function DiskReport { $DiskReportHeader = @" <table> <tr> <td colspan="6"><h3>Disk Report</h3> <h4>Drive(s) listed below have less than $thresholdspace % free space. Disk within the thresholds specified are colored to identify them easily</h4> </td> </tr> <tr> <th>Drive</th> <th>Drive Label</th> <th>Total Capacity (GB)</th> <th>Used Capacity (GB) </th> <th>Free Space (GB) </th> <th>Freespace %</th> </tr> "@ Add-Content "$Path\$OutputFile" $DiskReportHeader $disks = Get-WmiObject win32_logicaldisk ComputerName $computer | Where-Object {$_.drivetype -eq 3} foreach ($item in $disks) { WriteDiskInfo "$Path\$OutputFile" $item.DeviceID $item.VolumeName $item.FreeSpace $item.Size } 28 How to build a daily systems report email on OpenManage Essentials Add-Content "$Path\$OutputFile" "</table><p></p>" } # Assemble to top processes that are consuming the highest amount of memory Function ProcessReport { $ProcessReportHeader = @" <table> <tr> <td colspan="6"><h3>Processes Report</h3> <h4>The following $ProccessNumToFetch processes are those consuming the highest amount of Working Set (WS) Memory (bytes) on $computer</h4></td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $ProcessReportHeader $TopProcesses = (Get-process -ComputerName $computer | select-object ws,name | sort-object –property WS -Descending | selectobject –First $ProccessNumToFetch | convertto-html -Fragment) | Add-Content "$Path\$OutputFile" Add-Content "$Path\$OutputFile" "<p></p>" } # Assemble Service Report Function ServiceReport { $ServiceReportHeader = @" <table> <tr> <td colspan="6"><h3>Services Report</h3> <h4>The following services are those which are set to Automatic startup type, yet are currently not running on $computer</h4></td> </tr> </table><p></p> "@ $Services = (Get-WmiObject -Class Win32_Service ComputerName $computer | Select-Object DisplayName,Name,StartMode,State | Where-Object {$_.StartMode -eq "Auto" -and $_.State -eq "Stopped"}) If ($Services -ne $null) { Add-Content "$Path\$OutputFile" $ServiceReportHeader $StopServices = (Get-WmiObject -Class Win32_Service ComputerName $computer | Select-Object DisplayName,Name,StartMode,State | Where-Object {$_.StartMode -eq "Auto" -and $_.State -eq "Stopped"} | ConvertTo-Html -Fragment) -replace "<table>",'<table>' | Add-Content "$Path\$OutputFile" Add-Content "$Path\$OutputFile" "<p></p>" } } #Assemble System Event Log Report Function SystemLogReport { $SysReportHeader = @" <table> <tr> <td colspan="6"><h3>System Event Report</h3> 29 How to build a daily systems report email on OpenManage Essentials <h4>The following is a list of the last $EventNum <b>System log</b> events that had an Event Type of either Warning or Error on $computer</h4></td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $SysReportHeader $SystemEvents = (Get-EventLog -ComputerName $computer -LogName System -EntryType Error,Warning -Newest $EventNum | Select-Object Message,Source,EntryType,TimeGenerated | ConvertTo-Html -Fragment) -replace "<table>",'<table style="text-align: left" >' | Add-Content "$Path\$OutputFile" Add-Content "$Path\$OutputFile" "<p></p>" } #Assemble Application Event Log Report Function AppLogReport { $AppReportHeader = @" <table> <tr> <td colspan="6"><h3>Application Event Report</h3> <h4>The following is a list of the last $EventNum <b>Application log</b> events that had an Event Type of either Warning or Error on $computer</h4></td> </tr> </table><p></p> "@ Add-Content "$Path\$OutputFile" $AppReportHeader $ApplicationEvents = (Get-EventLog -ComputerName $computer -LogName Application -EntryType Error,Warning -Newest $EventNum | Select-Object Message,Source,EntryType,TimeGenerated | ConvertTo-Html Fragment) -replace "<table>",'<table style="text-align: left">' | Add-Content "$Path\$OutputFile" Add-Content "$Path\$OutputFile" "<p></p>" } # Run Main Report Get-DailyHTMLReport $args[0] 30
© Copyright 2024