|
You can take advantage of Powershell capabilities, along
with the PowerTools for OpenXml cmdlets in order to send bulk mail containing Open
Xml Documents to a group of people. The
following sample shows how to use the Export-OpenXmlSpreadsheet Open Xml Power
Tools cmdlet and the .NET send email built-in capability to send either periodical
or ad-hoc (alerts, maybe!) server
statistics to a group of users by email.
Given the object-oriented nature of PowerShell and the ease
of connection against .Net libraries, you can work with the prebuilt email
classes that come along with the .Net framework in order to construct an email
message (in this sample including a spreadsheet containing system information
created by using the Export-OpenXmlSpreadsheet Open Xml Power Tools cmdlet) and
send it to a list of addresses. Here is the script code:
# Passes an email address array to the script as parameter
param(
[string[]]
$Emails = $(throw "Specify email addresses")
)
# Sets the path to temporarily store the Spreadsheet
$CPUInformationPath = $env:temp+"\CPU.xlsx"
# Creates the Spreadsheet
Get-Process | Sort-Object -Property CPU -Descending | Select-Object -Property
Name, CPU -First 10 | Export-OpenXmlSpreadsheet
-OutputPath $CPUInformationPath -Chart -ChartType Column -ColumnsToChart
Name,CPU -HeaderColumn Name
# Configures the mail client
$SmtpClient = New-Object System.Net.Mail.SmtpClient
$SmtpClient.Host = "mail.staffdotnet.com"
# Creates and configures the mail message
$msg = New-Object System.Net.Mail.MailMessage
$msg.From = "notifications@staffdotnet.com"
$msg.Subject = "CPU report"
$msg.Body = (@"
CPU report
For
$(Get-Content env:COMPUTERNAME) at
$((Get-Date).ToString("yyyy-MM-dd hh:mm:ss tt"))
"@)
# Attaches the Spreadsheet to the mail message
$attachment = New-Object System.Net.Mail.Attachment($CPUInformationPath)
$msg.Attachments.Add($attachment)
# Sets the email addresses
foreach($email in $Emails)
{
$msg.To.Add($email)
}
# Sends the email
$SMTPClient.Send($msg)
And… that’s it! A very simple script which allows you to
send CPU usage statistics to a group of users!
You can call this script with email addresses directly at the command line,
> .\sendReport.ps1 'address1@staffdotnet.com','address2@staffdotnet.com'
or you can feed it with a list from a text document
> .\sendReport.ps1 @(Get-Content emailAddresses.txt)
|