<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Exchange Server Pro &#187; PowerShell</title>
	<atom:link href="http://exchangeserverpro.com/tag/powershell/feed" rel="self" type="application/rss+xml" />
	<link>http://exchangeserverpro.com</link>
	<description>Microsoft Exchange Server News - Tips - Tutorials</description>
	<lastBuildDate>Fri, 03 Feb 2012 12:36:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Using Test-Mailflow with Exchange 2003 Servers</title>
		<link>http://exchangeserverpro.com/test-mailflow-exchange-2003-servers</link>
		<comments>http://exchangeserverpro.com/test-mailflow-exchange-2003-servers#comments</comments>
		<pubDate>Sun, 04 Dec 2011 12:32:49 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Exchange 2003]]></category>
		<category><![CDATA[Exchange 2007]]></category>
		<category><![CDATA[Exchange 2010]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[Test-Mailflow]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4300</guid>
		<description><![CDATA[How to use the Test-Mailflow cmdlet in Exchange 2007/2010 to verify mail flow for an Exchange 2003 server.]]></description>
			<content:encoded><![CDATA[<p>One of the challenges of managing a large <a href="http://exchangeserverpro.com">Exchange Server</a> environment is that you often need to support multiple versions of Exchange.</p>
<p>That means that often when you write a <a href="http://exchangeserverpro.com/tag/powershell">PowerShell</a> script you need to account for servers running different versions and adjust accordingly. It can turn a simple scripting exercise into a big task.</p>
<p>Recently I was looking at ways to include our Exchange 2003 servers in some monitoring scripts that are already running for Exchange 2007/2010 servers. I wanted to perform a mail flow test for the Exchange 2003 servers, because that is a test that (if successful) very quickly confirms a lot of the elements involved in email availability are in fact healthy (ie the server is up, reachable, accepting SMTP connections, processing mail queues, the Information Store is running, and more).</p>
<p>For Exchange 2007/2010 the <a href="http://technet.microsoft.com/en-us/library/aa995894.aspx">Test-Mailflow</a> cmdlet can be used for these. You can build it into a <a href="http://exchangeserverpro.com/health-check-exchange-2010-mailbox-server">health check script</a> if you want to. But if you try to run it against an Exchange 2003 server you&#8217;ll get an error like this:</p>
<pre>
[PS] C:\&gt;Test-Mailflow -Identity EX2007SERVER -TargetMailboxServer EX2003SERVER

Test-Mailflow : "EX2003SERVER" is running a previous version of Exchange and does not support this task.
At line:1 char:14
+ Test-Mailflow &lt;&lt;&lt;&lt;  -Identity EX2007SERVER -TargetMailboxServer EX2003SERVER
    + CategoryInfo          : InvalidArgument: (:) [Test-Mailflow], OperationOnOldServerException
    + FullyQualifiedErrorId : 642F2C5C,Microsoft.Exchange.Monitoring.TestMailFlow</pre>
<p>However, if the Exchange 2003 server is in the same organization you can use a different parameter with Test-Mailflow to achieve the same result. All you need is an email address for one of the mailboxes on the Exchange 2003 server. You might want to create a mailbox on each of your Exchange 2003 servers (or even each of the databases on those servers) specifically for this purpose.</p>
<p>Then you simply run the Test-Mailflow cmdlet with the -TargetEmailAddress parameter instead of the -TargetMailboxServer parameter.</p>
<pre>[PS] C:\&gt;Test-Mailflow -Identity EX2007SERVER -TargetEmailAddress EX2003SERVER_test@domain.com

TestMailflowResult         MessageLatencyTime          IsRemoteTest
------------------         ------------------          ------------
Success                    00:00:19.5014893            True</pre>
<p>As you can see this is a nice, simple way to test your Exchange 2003 server health using PowerShell.</p>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/powershell-configuring-settings-multiple-exchange-mailbox-databases" title="PowerShell: Configuring Settings on Multiple Exchange Mailbox Databases">PowerShell: Configuring Settings on Multiple Exchange Mailbox Databases</a></li><li><a href="http://exchangeserverpro.com/error-outlook-unable-recover-items-folder" title="Error: Outlook Was Unable to Recover Some or All of the Items in this Folder">Error: Outlook Was Unable to Recover Some or All of the Items in this Folder</a></li><li><a href="http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email" title="How to Set Up an Automated Exchange 2010 Database Backup Alert Email">How to Set Up an Automated Exchange 2010 Database Backup Alert Email</a></li><li><a href="http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups" title="PowerShell Script: Check Exchange 2010 Database Backups">PowerShell Script: Check Exchange 2010 Database Backups</a></li><li><a href="http://exchangeserverpro.com/exchange-2010-test-servicehealth" title="Using Test-ServiceHealth for Exchange Server Health Checks">Using Test-ServiceHealth for Exchange Server Health Checks</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/test-mailflow-exchange-2003-servers">Using Test-Mailflow with Exchange 2003 Servers</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/test-mailflow-exchange-2003-servers/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Health Check an Exchange 2010 Mailbox Server</title>
		<link>http://exchangeserverpro.com/health-check-exchange-2010-mailbox-server</link>
		<comments>http://exchangeserverpro.com/health-check-exchange-2010-mailbox-server#comments</comments>
		<pubDate>Mon, 21 Nov 2011 11:51:55 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Exchange 2010]]></category>
		<category><![CDATA[Mailbox Server]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4275</guid>
		<description><![CDATA[Get this free PowerShell script for performing a quick health check of your Exchange Server 2010 mailbox servers.]]></description>
			<content:encoded><![CDATA[<p>How many times each day do you get asked, <em>&#8220;Is there a problem with the Exchange server?</em>&#8221;</p>
<p>If you&#8217;re like me then you get asked this question at least once per day. Of course there usually isn&#8217;t anything wrong with our Exchange servers <img src='http://exchangeserverpro.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  but once the question has been asked then you have no choice but to investigate and confirm that everything is okay.</p>
<p>In this article I&#8217;m going to demonstrate how you can quickly check the health of your <a href="http://exchangeserverpro.com">Exchange Server 2010</a> mailbox servers, and share a script with you that can help to speed up this task.</p>
<p>Exchange Server 2010 has a series of PowerShell cmdlets that make it easy to do a health check of <a href="http://exchangeserverpro.com/exchange-2010-server-roles">mailbox servers</a>. For example, we can:</p>
<ul>
<li>Run <a href="http://exchangeserverpro.com/exchange-2010-test-servicehealth">Test-Servicehealth</a> to check the required services are all running</li>
<li>Run <a href="http://technet.microsoft.com/en-us/library/bb124924.aspx">Get-MailboxDatabase</a> to check whether the mailbox databases are mounted</li>
<li>Run <a href="http://technet.microsoft.com/en-us/library/bb123681.aspx">Test-MapiConnectivity</a> to verify that the databases are responding to MAPI requests</li>
<li>Run <a href="http://technet.microsoft.com/en-us/library/aa995894.aspx">Test-MailFlow</a> to confirm that email is able to pass successfully between two servers</li>
<li>Run <a href="http://technet.microsoft.com/en-us/library/dd298044.aspx">Get-MailboxDatabaseCopyStatus</a> for <a href="http://exchangeserverpro.com/exchange-server-2010-database-availability-group-installation-step-by-step">DAG</a> members to check the database copy status, queues, and content indexes</li>
</ul>
<p>That&#8217;s quite a few cmdlets to run, especially if we&#8217;ve got more than one mailbox server in the organization. And of course each of those cmdlets needs to run and show you output that you need to interpret.</p>
<p>I like to make life a bit easier and use PowerShell scripts to speed up these types of tasks. So naturally I put together a script for performing all of the above tests (and a few more) on my mailbox servers and display a nice simple colour-coded output so that I can tell at a glance whether there might be a problem.</p>
<p>This isn&#8217;t designed to do a diagnosis of any problems, it just checks the fundamentals and gives me a simple pass/fail and a few other indicators that I can then troubleshoot further if necessary.</p>
<p class="alert"><strong>Download the script file here:</strong> <a class="downloadlink" href="http://exchangeserverpro.com/wp-content/plugins/download-monitor/download.php?id=Test-MailboxServer.zip" title="Version 1.1 downloaded 834 times" >Test-MailboxServer.ps1</a> (downloaded 834 times so far)</p>
<p>Extract <strong>Test-MailboxServer.ps1</strong> from the Zip file and run it in your Exchange Management Shell to see output such as this:</p>
<p><img class="aligncenter size-full wp-image-4276" title="exchange-2010-test-mailboxserver-health-01" src="http://exchangeserverpro.com/wp-content/uploads/2011/11/exchange-2010-test-mailboxserver-health-01.jpg" alt="" width="580" height="446" /></p>
<p>If you have any questions or bugs to report please let me know in the comments below.</p>
<p><strong>Change log:</strong></p>
<ul>
<li>V1.0, 20/11/2011 &#8211; Initial version</li>
<li>V1.1, 10/01/2011 &#8211; Fixed $null&#8217;s, bugs with Recovery DBs, and ping failure scenarios</li>
</ul>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/powershell-script-check-exchange-mailbox-database-backup-time" title="PowerShell Script: Check Exchange Mailbox Database Last Backup Time">PowerShell Script: Check Exchange Mailbox Database Last Backup Time</a></li><li><a href="http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email" title="How to Set Up an Automated Exchange 2010 Database Backup Alert Email">How to Set Up an Automated Exchange 2010 Database Backup Alert Email</a></li><li><a href="http://exchangeserverpro.com/list-users-access-exchange-mailboxes" title="How to List all Users Who Have Access to Other Exchange Mailboxes">How to List all Users Who Have Access to Other Exchange Mailboxes</a></li><li><a href="http://exchangeserverpro.com/generate-html-report-exchange-2010-environment" title="How to Generate a HTML Report of Your Exchange 2010 Environment">How to Generate a HTML Report of Your Exchange 2010 Environment</a></li><li><a href="http://exchangeserverpro.com/clone-mailbox-database-configuration" title="Exchange 2007/2010: How to Clone a Mailbox Database Configuration">Exchange 2007/2010: How to Clone a Mailbox Database Configuration</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/health-check-exchange-2010-mailbox-server">How to Health Check an Exchange 2010 Mailbox Server</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/health-check-exchange-2010-mailbox-server/feed</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>How to Set Up an Automated Exchange 2010 Database Backup Alert Email</title>
		<link>http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email</link>
		<comments>http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email#comments</comments>
		<pubDate>Thu, 10 Nov 2011 11:50:21 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Backups]]></category>
		<category><![CDATA[Exchange 2010]]></category>
		<category><![CDATA[Mailbox Server]]></category>
		<category><![CDATA[Monitoring]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Scripting]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4242</guid>
		<description><![CDATA[Learn how to use PowerShell to automatically monitor your Exchange Server 2010 database backups and send an alert email when recent backups have not been successful.]]></description>
			<content:encoded><![CDATA[<p>In recent articles I&#8217;ve taken you step by step through some techniques for <a href="http://exchangeserverpro.com/powershell-how-to-send-email">sending email from PowerShell scripts</a>. If you haven&#8217;t read those articles yet you can find them here:</p>
<ul>
<li><a href="http://exchangeserverpro.com/powershell-how-to-send-email">Part 1 – How to Send SMTP Email Using PowerShell</a></li>
<li><a href="http://exchangeserverpro.com/powershell-email-message-body">Part 2 - How to Add a Message Body to Emails Sent from Scripts</a></li>
<li><a href="http://exchangeserverpro.com/powershell-send-html-email">Part 3 - How to Add a HTML Message Body to Emails Sent from Scripts</a></li>
<li><a href="http://exchangeserverpro.com/powershell-html-email-formatting">Part 4 - How to Create Formatted HTML Output from Scripts</a></li>
</ul>
<p>I also shared with you a script that can be used to <a href="http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups">check Exchange Server 2010 database backups</a> and alert you to any that have not had a recent backup.</p>
<p>Now it&#8217;s time to bring all of that information together and demonstrate how you can set up an automated database backup alert email for your <a href="http://exchangeserverpro.com">Exchange Server 2010</a> environment.</p>
<p>The two components of this are:</p>
<ul>
<li>The PowerShell script itself (we&#8217;ll use the one mentioned earlier but with some modifications to email-enable it)</li>
<li>Task Scheduler for automatically running the script each day</li>
</ul>
<h2>Script for Exchange Server 2010 Database Backup Email Alerts</h2>
<p>To email-enable the script I&#8217;ve made just a few modifications. The original script used this conditional logic to display the report in the PowerShell window.</p>
<pre>#If alert flag is true output the report
if ($alertflag -eq $true )
{
	Write-Host "The following databases have not been backed up in" $threshold "hours."
	$alerts | ft -AutoSize
}
else
{
	Write-Host "No backup alerts required."
}</pre>
<p>To change this to send an email alert we can use this code instead:</p>
<pre>#If alert flag is true send the email alert
if ($alertflag -eq $true )
{
	#HTML styles for nice formatting
        $style = "&lt;style&gt;BODY{font-family: Arial; font-size: 10pt;}"
	$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
	$style = $style + "TH{border: 1px solid black; background: #CC0000; padding: 5px; color: #FFFFFF;}"
	$style = $style + "TD{border: 1px solid black; padding: 5px; }"
	$style = $style + "&lt;/style&gt;"

        #SMTP options for sending the report email
	$smtpServer = "ho-ex2010-caht1.exchangeserverpro.net"
	$smtpFrom = "reports@exchangeserverpro.net"
	$smtpTo = "administrator@exchangeserverpro.net"
	$messageSubject = "Exchange Backup Alerts"

        $intro = "The following databases have not been backed up in " + $threshold + " hours.&lt;BR&gt;&lt;BR&gt;"
	$report = $alerts | ConvertTo-Html -Fragment

	#Get ready to send email message
	$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
	$message.Subject = $messageSubject
	$message.IsBodyHTML = $true
	$message.Body = ConvertTo-Html -Body "$intro $report" -Head $style

	#Send email message
	$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
	$smtp.Send($message)

}</pre>
<p>If any parts of that don&#8217;t make sense just refer to the previous tutorials on sending email with PowerShell.</p>
<p>Here is the full script code we&#8217;ll be using for this:</p>
<pre>#
#.SYNOPSIS
#Checks the backup timestamps for the servers
#and alerts if a database hasn't been backed up
#in the last 48 hours
#
#.EXAMPLE
#.\Check-DatabaseBackups.ps1
#

#...................................
# Variables
#...................................

#Suppress errors
$ErrorActionPreference = "SilentlyContinue"
$WarningPreference = "SilentlyContinue"

#Load the Exchange 2010 snap-in
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

#Array to hold alert objects
$alerts = @()

#Set alert threshold for hours since last successful backup
$day = (Get-Date).DayOfWeek
if ($day -eq "Monday")
{
	[int]$threshold = 72
}
else
{
	[int]$threshold = 48
}

#Current time stamp to compare with databases
$now = [DateTime]::Now

#...................................
# Functions
#...................................

#...................................
# Script
#...................................

#Get all Mailbox and Public Folder databases
Write-Host -ForegroundColor Gray "Getting database list..."
$dbs = Get-MailboxDatabase -Status
$dbs = $dbs += Get-PublicFolderDatabase -Status

#Check each database for most recent backup
foreach ($db in $dbs)
{
	Write-Host -ForegroundColor Gray "Checking" $db.name"..."

	$lastbackup = @{}
	$ago = @()
	[bool]$alertflag = $false

	if ( $db.LastFullBackup -eq $null -and $db.LastIncrementalBackup -eq $nul)
	{
		$lastbackup.time = "Never"
		$lastbackup.type = "Never"
		[string]$ago = "Never"
	}
	elseif ( $db.LastFullBackup -lt $db.LastIncrementalBackup )
	{
		$lastbackup.time = $db.LastIncrementalBackup
		$lastbackup.type = "Incremental"
		[int]$ago = ($now - $lastbackup.time).TotalHours
		$ago = "{0:N0}" -f $ago
	}
	elseif ( $db.LastIncrementalBackup -lt $db.LastFullBackup )
	{
		$lastbackup.time = $db.LastFullBackup
		$lastbackup.type = "Full"
		[int]$ago = ($now - $lastbackup.time).TotalHours
		$ago = "{0:N0}" -f $ago
	}

	if ($db.IsMailboxDatabase -eq $true) {$dbtype = "Mailbox"}
	if ($db.IsPublicFolderDatabase -eq $true) {$dbtype = "Public Folder"}

	#If backup time stamp older than threshold set alert flag and create object for alerting
	if ( $ago -gt $threshold -or $ago -eq "Never")
	{
		$alertflag = $true
		$dbObj = New-Object PSObject
		if ( $dbtype -eq "Public Folder")
		{
			$dbObj | Add-Member NoteProperty -Name "Server/DAG" -Value $db.Server
		}
		else
		{
			$dbObj | Add-Member NoteProperty -Name "Server/DAG" -Value $db.MasterServerOrAvailabilityGroup
		}
		$dbObj | Add-Member NoteProperty -Name "Database" -Value $db.name
		$dbObj | Add-Member NoteProperty -Name "Database Type" -Value $dbtype
		$dbObj | Add-Member NoteProperty -Name "Last Backup Type" -Value $lastbackup.type
		$dbObj | Add-Member NoteProperty -Name "Hrs Ago" -Value $ago
		$dbObj | Add-Member NoteProperty -Name "Time Stamp" -Value $lastbackup.time
		$dbObj | Add-Member NoteProperty -Name "Currently Running" -Value $db.backupinprogress
		$alerts = $alerts += $dbObj
	}
}

#If alert flag is true send the email alert
if ($alertflag -eq $true )
{
	#HTML styles for nice formatting
        $style = "&lt;style&gt;BODY{font-family: Arial; font-size: 10pt;}"
	$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
	$style = $style + "TH{border: 1px solid black; background: #CC0000; padding: 5px; color: #FFFFFF;}"
	$style = $style + "TD{border: 1px solid black; padding: 5px; }"
	$style = $style + "&lt;/style&gt;"

        #SMTP options for sending the report email
	$smtpServer = "ho-ex2010-caht1.exchangeserverpro.net"
	$smtpFrom = "reports@exchangeserverpro.net"
	$smtpTo = "administrator@exchangeserverpro.net"
	$messageSubject = "Exchange Backup Alerts"

        $intro = "The following databases have not been backed up in " + $threshold + " hours.&lt;BR&gt;&lt;BR&gt;"
	$report = $alerts | ConvertTo-Html -Fragment

	#Get ready to send email message
	$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
	$message.Subject = $messageSubject
	$message.IsBodyHTML = $true
	$message.Body = ConvertTo-Html -Body "$intro $report" -Head $style

	#Send email message
	$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
	$smtp.Send($message)

}</pre>
<p>If you&#8217;re using this script in your environment you will need to change the SMTP options to suit.</p>
<p>Save the script as Get-DailyBackupAlerts.ps1 in a folder called C:\Scripts on the server where you would like it to run each day. Note that the script depends on the Exchange Server 2010 management tools, so they will also need to be installed.</p>
<h2>Using Task Scheduler to Run PowerShell Scripts</h2>
<p>Now we need to configure the scheduled task in Task Scheduler. On a Windows Server 2008 server you&#8217;ll find this in the <strong>Administrative Tools</strong>. After you&#8217;ve launched Task Scheduler click on <strong>Create Task</strong>.</p>
<p><img class="aligncenter size-full wp-image-4243" title="task-scheduler-powershell-script-01" src="http://exchangeserverpro.com/wp-content/uploads/2011/11/task-scheduler-powershell-script-01.jpg" alt="" width="305" height="290" />Give the task a meaningful name, set it to <strong>Run whether user is logged on or not</strong>, and also if necessary change the user account that it will run as (you may wish to create a special Exchange administrative account with a strong password for running these types of scripts).</p>
<p><img class="aligncenter size-full wp-image-4244" title="task-scheduler-powershell-script-02" src="http://exchangeserverpro.com/wp-content/uploads/2011/11/task-scheduler-powershell-script-02.jpg" alt="" width="590" height="439" />On the <strong>Triggers</strong> tab click new and add a <strong>Weekly</strong> trigger for each of your normal business days that you want the script to run (eg Monday &#8211; Friday). Set the <strong>Start</strong> time to suit your normal backups finishing time and your own work schedule.</p>
<p><img class="aligncenter size-full wp-image-4245" title="task-scheduler-powershell-script-03" src="http://exchangeserverpro.com/wp-content/uploads/2011/11/task-scheduler-powershell-script-03.jpg" alt="" width="556" height="439" /></p>
<p>On the <strong>Actions</strong> tab click <strong>New</strong> and add an action of Start a program. Configure the program of <strong>powershell.exe</strong> and the arguments <strong>-command &#8220;c:\scripts\get-dailybackupalerts.ps1&#8243;</strong></p>
<p><img class="aligncenter size-full wp-image-4248" title="task-scheduler-powershell-script-04" src="http://exchangeserverpro.com/wp-content/uploads/2011/11/task-scheduler-powershell-script-04.jpg" alt="" width="552" height="428" /></p>
<p>&nbsp;</p>
<p>Click <strong>OK</strong> to finish creating the new task. You will be prompted to enter the credentials for the account that you configured the task to run as.</p>
<p>Now you can test the scheduled task by right-clicking on it in the Task Scheduler Library and choosing <strong>Run</strong>.</p>
<p><img class="aligncenter size-full wp-image-4247" title="task-scheduler-powershell-script-05" src="http://exchangeserverpro.com/wp-content/uploads/2011/11/task-scheduler-powershell-script-05.jpg" alt="" width="503" height="244" />Assuming you have some databases that have not backed up recently you should receive an alert email shortly after running the scheduled task.</p>
<p><em>Note: if your backups are all up to date you can test the script by changing the <strong>$threshold</strong> variable to something very low such as <strong>1</strong>.</em></p>
<p><img class="aligncenter size-full wp-image-4249" title="exchange-2010-backup-alert-email" src="http://exchangeserverpro.com/wp-content/uploads/2011/11/exchange-2010-backup-alert-email.jpg" alt="" width="590" height="229" /></p>
<p>&nbsp;</p>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups" title="PowerShell Script: Check Exchange 2010 Database Backups">PowerShell Script: Check Exchange 2010 Database Backups</a></li><li><a href="http://exchangeserverpro.com/powershell-script-check-exchange-mailbox-database-backup-time" title="PowerShell Script: Check Exchange Mailbox Database Last Backup Time">PowerShell Script: Check Exchange Mailbox Database Last Backup Time</a></li><li><a href="http://exchangeserverpro.com/avoid-running-transaction-log-disk-space-exchange-servers" title="Avoid Running Out of Transaction Log Disk Space on Exchange Servers">Avoid Running Out of Transaction Log Disk Space on Exchange Servers</a></li><li><a href="http://exchangeserverpro.com/test-mailflow-exchange-2003-servers" title="Using Test-Mailflow with Exchange 2003 Servers">Using Test-Mailflow with Exchange 2003 Servers</a></li><li><a href="http://exchangeserverpro.com/health-check-exchange-2010-mailbox-server" title="How to Health Check an Exchange 2010 Mailbox Server">How to Health Check an Exchange 2010 Mailbox Server</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email">How to Set Up an Automated Exchange 2010 Database Backup Alert Email</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Script: Check Exchange 2010 Database Backups</title>
		<link>http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups</link>
		<comments>http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups#comments</comments>
		<pubDate>Sun, 06 Nov 2011 11:23:58 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[Features]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Backups]]></category>
		<category><![CDATA[Exchange 2010]]></category>
		<category><![CDATA[Exchange Management Shell]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Reporting]]></category>
		<category><![CDATA[Scripting]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4227</guid>
		<description><![CDATA[A PowerShell script that can be used to monitor the backup time stamps on Exchange Server 2010 databases.]]></description>
			<content:encoded><![CDATA[<p>In almost any <a href="http://exchangeserverpro.com">Exchange Server 2010</a> environment there will be a good reason for adding some additional monitoring of backups.</p>
<p>Perhaps the environment is large enough that the backups are managed by a separate team to the Exchange administrators, and so the Exchange admins just want to keep an eye on their database backups. Or even in a smaller environment the administrators may just want to be sure that their backup software isn&#8217;t reporting successful backups when in fact they may be failing.</p>
<p>In this post I will demonstrate a PowerShell script that you can run in an Exchange Server 2010 environment to report on any databases that have not successfully backed up in the last 48 hours. Let&#8217;s take a look at how this works.</p>
<p>Firstly, backup time stamps are retrievable using the <a href="http://technet.microsoft.com/en-us/library/bb124924.aspx">Get-MailboxDatabase</a> cmdlet for mailbox databases, or <a href="http://technet.microsoft.com/en-us/library/aa998827.aspx">Get-PublicFolderDatabase</a> for public folder databases. Here is an example:</p>
<pre>PS C:\Scripts&gt; Get-MailboxDatabase -Status | ft name,last* -auto

Name     LastFullBackup       LastIncrementalBackup LastDifferentialBackup LastCopyBackup
----     --------------       --------------------- ---------------------- --------------
MB-HO-01 11/6/2011 1:40:19 PM
MB-HO-02
MB-HO-03
MB-BR-01</pre>
<p>You can see that one of the databases above has been backed up, but the others have not. In a script that checks both mailbox and public folder databases we could use this code to generate the report.</p>
<pre>$dbs = Get-MailboxDatabase -Status
$dbs = $dbs += Get-PublicFolderDatabase -Status
$dbs | ft name,last*</pre>
<p>Now we can see both the mailbox and the public folder databases.</p>
<pre>Name                    LastFullBackup          LastIncrementalBackup   LastDifferentialBackup  LastCopyBackup
----                    --------------          ---------------------   ----------------------  --------------
MB-HO-01                11/6/2011 1:40:19 PM
MB-HO-02
MB-HO-03
MB-BR-01
PF-HO-01                11/6/2011 1:40:20 PM
PF-BR-01</pre>
<p>It would be a simple matter to run that command and read the output every single day, but that would not be the most efficient way of checking database backups. There could be dozens or even hundreds of databases in that output, and we&#8217;d have to mentally perform the calculations to determine whether the backup time stamp is within the last 48 hours or not.</p>
<p>Instead we want to only to see databases that have not been backed up within the 48 hour threshold. To do this we can use some <a href="http://technet.microsoft.com/en-us/library/ff730960.aspx">date maths</a>. Because we&#8217;ve already retrieved the database objects into a collection called <strong>$dbs</strong> we can loop through them to perform the date calculations like this. Note that in this example only <a href="http://exchangeserverpro.com/introduction-to-exchange-server-2010-backup-and-recovery">Full and Incremental backups</a> are being considered.</p>
<pre>foreach ($db in $dbs)
{
	Write-Host -ForegroundColor Gray "Checking" $db.name"..."

	$lastbackup = @{}
	$ago = @()
	[bool]$alertflag = $false

	if ( $db.LastFullBackup -eq $nul -and $db.LastIncrementalBackup -eq $nul)
	{
		$lastbackup.time = "Never"
		$lastbackup.type = "Never"
		[string]$ago = "Never"
	}
	elseif ( $db.LastFullBackup -lt $db.LastIncrementalBackup )
	{
		$lastbackup.time = $db.LastIncrementalBackup
		$lastbackup.type = "Incremental"
		[int]$ago = ($now - $lastbackup.time).TotalHours
		$ago = "{0:N0}" -f $ago
	}
	elseif ( $db.LastIncrementalBackup -lt $db.LastFullBackup )
	{
		$lastbackup.time = $db.LastFullBackup
		$lastbackup.type = "Full"
		[int]$ago = ($now - $lastbackup.time).TotalHours
		$ago = "{0:N0}" -f $ago
	}
}</pre>
<p>One of three possible scenarios will be true:</p>
<ul>
<li>If the database has not been backed up at all then both Full and Incremental time stamps will be nul, so all of the resulting values are set to &#8220;Never&#8221;</li>
<li>If the most recent backup was an Incremental then the type is set to &#8220;Incremental&#8221; and the <strong>$ago</strong> variable is set to the number of hours that has passed since that Incremental backup finished</li>
<li>If the most recent backup was a Full then the type is set to &#8220;Full&#8221; and the <strong>$ago</strong> variable is set to the number of hours that has passed since that Full backup finished</li>
</ul>
<p>Now, because we&#8217;re only interested in databases that haven&#8217;t backed up in the last 48 hours (or have never been backed up at all) we can compare the $ago variable to our threshold of 48 hours, and if an alert needs to be raised set the alert flag to <strong>True</strong> and create an object with all of the desired information for our report.</p>
<pre>if ( $ago -gt $threshold -or $ago -eq "Never")
	{
		$alertflag = $true
		$dbObj = New-Object PSObject
		$dbObj | Add-Member NoteProperty -Name "Server/DAG" -Value $db.MasterServerOrAvailabilityGroup
		$dbObj | Add-Member NoteProperty -Name "Database" -Value $db.name
		$dbObj | Add-Member NoteProperty -Name "Database Type" -Value $dbtype
		$dbObj | Add-Member NoteProperty -Name "Last Backup Type" -Value $lastbackup.type
		$dbObj | Add-Member NoteProperty -Name "Hrs Ago" -Value $ago
		$dbObj | Add-Member NoteProperty -Name "Time Stamp" -Value $lastbackup.time
		$alerts = $alerts += $dbObj
	}</pre>
<p>That code actually goes inside the <a href="http://technet.microsoft.com/en-us/library/ee176828.aspx">ForEach loop</a> for the $dbs collection.</p>
<p>The final piece of the script is the report itself. We output it based on whether the alert flag is set to True or False.</p>
<pre>if ($alertflag = $true )
{
	Write-Host "The following databases have not been backed up in" $threshold "hours."
	$alerts | ft -AutoSize
}
else
{
	Write-Host "No backup alerts required."
}</pre>
<p>This example outputs the report to the PowerShell window but you could write your <a href="http://exchangeserverpro.com/powershell-how-to-send-email">PowerShell script to send an email report</a> instead if you wish.</p>
<p>Here is an example report:</p>
<pre>PS C:\Scripts&gt; .\Check-DatabaseBackups.ps1
Getting database list...
Checking MB-HO-01 ...
Checking MB-HO-02 ...
Checking MB-HO-03 ...
Checking MB-BR-01 ...
Checking PF-HO-01 ...
Checking PF-BR-01 ...
The following databases have not been backed up in 48 hours.

Server/DAG     Database Database Type Last Backup Type Hrs Ago Time Stamp
----------     -------- ------------- ---------------- ------- ----------
dag-headoffice MB-HO-02 Mailbox       Never            Never   Never
dag-headoffice MB-HO-03 Mailbox       Never            Never   Never
BR-EX2010-MB   MB-BR-01 Mailbox       Never            Never   Never
BR-EX2010-MB   PF-BR-01 Public Folder Never            Never   Never</pre>
<p>And here is the complete script.</p>
<pre>#
#.SYNOPSIS
#Checks the backup timestamps for the servers
#and alerts if a database hasn't been backed up
#in the last 48 hours
#
#.EXAMPLE
#.\Check-DatabaseBackups.ps1
#

#...................................
# Variables
#...................................

$ErrorActionPreference = "SilentlyContinue"
$WarningPreference = "SilentlyContinue"

$alerts = @()
[int]$threshold = 48

$now = [DateTime]::Now

#...................................
# Script
#...................................

#Get all Mailbox and Public Folder databases
Write-Host -ForegroundColor Gray "Getting database list..."
$dbs = Get-MailboxDatabase -Status
$dbs = $dbs += Get-PublicFolderDatabase -Status

#Check each database for most recent backup
foreach ($db in $dbs)
{
	Write-Host -ForegroundColor Gray "Checking" $db.name"..."

	$lastbackup = @{}
	$ago = @()
	[bool]$alertflag = $false

	if ( $db.LastFullBackup -eq $null -and $db.LastIncrementalBackup -eq $nul)
	{
		$lastbackup.time = "Never"
		$lastbackup.type = "Never"
		[string]$ago = "Never"
	}
	elseif ( $db.LastFullBackup -lt $db.LastIncrementalBackup )
	{
		$lastbackup.time = $db.LastIncrementalBackup
		$lastbackup.type = "Incremental"
		[int]$ago = ($now - $lastbackup.time).TotalHours
		$ago = "{0:N0}" -f $ago
	}
	elseif ( $db.LastIncrementalBackup -lt $db.LastFullBackup )
	{
		$lastbackup.time = $db.LastFullBackup
		$lastbackup.type = "Full"
		[int]$ago = ($now - $lastbackup.time).TotalHours
		$ago = "{0:N0}" -f $ago
	}

	if ($db.IsMailboxDatabase -eq $true) {$dbtype = "Mailbox"}
	if ($db.IsPublicFolderDatabase -eq $true) {$dbtype = "Public Folder"}

	#If backup time stamp older than threshold set alert flag and create object for alerting
	if ( $ago -gt $threshold -or $ago -eq "Never")
	{
		$alertflag = $true
		$dbObj = New-Object PSObject
		$dbObj | Add-Member NoteProperty -Name "Server/DAG" -Value $db.MasterServerOrAvailabilityGroup
		$dbObj | Add-Member NoteProperty -Name "Database" -Value $db.name
		$dbObj | Add-Member NoteProperty -Name "Database Type" -Value $dbtype
		$dbObj | Add-Member NoteProperty -Name "Last Backup Type" -Value $lastbackup.type
		$dbObj | Add-Member NoteProperty -Name "Hrs Ago" -Value $ago
		$dbObj | Add-Member NoteProperty -Name "Time Stamp" -Value $lastbackup.time
		$alerts = $alerts += $dbObj
	}
}

#If alert flag is true output the report
if ($alertflag = $true )
{
	Write-Host "The following databases have not been backed up in" $threshold "hours."
	$alerts | ft -AutoSize
}
else
{
	Write-Host "No backup alerts required."
}</pre>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email" title="How to Set Up an Automated Exchange 2010 Database Backup Alert Email">How to Set Up an Automated Exchange 2010 Database Backup Alert Email</a></li><li><a href="http://exchangeserverpro.com/powershell-configuring-settings-multiple-exchange-mailbox-databases" title="PowerShell: Configuring Settings on Multiple Exchange Mailbox Databases">PowerShell: Configuring Settings on Multiple Exchange Mailbox Databases</a></li><li><a href="http://exchangeserverpro.com/powershell-script-check-exchange-mailbox-database-backup-time" title="PowerShell Script: Check Exchange Mailbox Database Last Backup Time">PowerShell Script: Check Exchange Mailbox Database Last Backup Time</a></li><li><a href="http://exchangeserverpro.com/test-mailflow-exchange-2003-servers" title="Using Test-Mailflow with Exchange 2003 Servers">Using Test-Mailflow with Exchange 2003 Servers</a></li><li><a href="http://exchangeserverpro.com/exchange-2010-test-servicehealth" title="Using Test-ServiceHealth for Exchange Server Health Checks">Using Test-ServiceHealth for Exchange Server Health Checks</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups">PowerShell Script: Check Exchange 2010 Database Backups</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to Send SMTP Email Using PowerShell (Part 4)</title>
		<link>http://exchangeserverpro.com/powershell-html-email-formatting</link>
		<comments>http://exchangeserverpro.com/powershell-html-email-formatting#comments</comments>
		<pubDate>Sun, 30 Oct 2011 12:02:13 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Email]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Scripting]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4203</guid>
		<description><![CDATA[Learn how to apply HTML styles to create nicely formatted HTML output from PowerShell scripts.]]></description>
			<content:encoded><![CDATA[<p>In the last part of this article series on <a href="http://exchangeserverpro.com/powershell-how-to-send-email">sending email using PowerShell</a> I demonstrated <a href="http://exchangeserverpro.com/powershell-send-html-email">how to create HTML emails from PowerShell scripts</a>.</p>
<ul>
<li><a href="http://exchangeserverpro.com/powershell-how-to-send-email">Part 1 &#8211; How to Send SMTP Email Using PowerShell</a></li>
<li><a href="http://exchangeserverpro.com/powershell-email-message-body">Part 2 - How to Add a Message Body to Emails Sent from Scripts</a></li>
<li><a href="http://exchangeserverpro.com/powershell-send-html-email">Part 3 - How to Add a HTML Message Body to Emails Sent from Scripts</a></li>
<li><strong>Part 4 - How to Create Formatted HTML Output from Scripts</strong></li>
</ul>
<p>One of the downsides to creating HTML output from PowerShell scripts is that the formatting is not very nice. The default formatting results in messages that look something like this.</p>
<p><img class="aligncenter size-full wp-image-4204" title="powershell-send-html-email" src="http://exchangeserverpro.com/wp-content/uploads/2011/10/powershell-send-html-email1.jpg" alt="" width="500" height="365" /></p>
<p>The HTML for that email message was created by piping the output from one command into the <a href="http://technet.microsoft.com/en-us/library/ee156817.aspx">ConvertTo-HTML</a> cmdlet. Fortunately ConvertTo-HTML has the <strong>-Head</strong> parameter that can be used to add style information to the HTML that it generates.</p>
<p>For example, by adding this line to the script used in the last article we can change the font to something a little nicer to look at.</p>
<pre>$style = "&lt; style&gt;BODY{font:arial 10pt;}&lt; /style&gt;"</pre>
<p><em>Note: extra spaces have been added to the style tags so that WordPress does not remove them.</em></p>
<p><em></em>Then modify the ConvertTo-HTML cmdlet to add the -Head parameter.</p>
<pre>$message.Body = Get-ExchangeServer | Select-Object Name,ServerRole | ConvertTo-Html -Head $style</pre>
<p>This time when the script is run the email looks like this instead.</p>
<p><img class="aligncenter size-full wp-image-4205" title="powershell-html-formatting-01" src="http://exchangeserverpro.com/wp-content/uploads/2011/10/powershell-html-formatting-01.jpg" alt="" width="579" height="378" /></p>
<p>That is a little better, but we can do a lot more. How about we add some more styles to the table and really make it look nice.</p>
<pre>$style = "&lt; style&gt;BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$style = $style + "TD{border: 1px solid black; padding: 5px; }"
$style = $style + "&lt; /style&gt;"</pre>
<p><em>Again note that extra spaces were added to the style tags above to preserve them in WordPress.</em></p>
<p>Now the script produces an email that looks like this.</p>
<p><img class="aligncenter size-full wp-image-4206" title="powershell-html-formatting-02" src="http://exchangeserverpro.com/wp-content/uploads/2011/10/powershell-html-formatting-02.jpg" alt="" width="594" height="432" /></p>
<p>Although this requires you to know a little bit about how HTML styles work, it is a pretty easy topic to learn and once you get a few working styles in your scripting tool kit you can just use them over and over again.</p>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/powershell-send-html-email" title="How to Send SMTP Email Using PowerShell (Part 3)">How to Send SMTP Email Using PowerShell (Part 3)</a></li><li><a href="http://exchangeserverpro.com/powershell-email-message-body" title="How to Send SMTP Email Using PowerShell (Part 2)">How to Send SMTP Email Using PowerShell (Part 2)</a></li><li><a href="http://exchangeserverpro.com/test-mailflow-exchange-2003-servers" title="Using Test-Mailflow with Exchange 2003 Servers">Using Test-Mailflow with Exchange 2003 Servers</a></li><li><a href="http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email" title="How to Set Up an Automated Exchange 2010 Database Backup Alert Email">How to Set Up an Automated Exchange 2010 Database Backup Alert Email</a></li><li><a href="http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups" title="PowerShell Script: Check Exchange 2010 Database Backups">PowerShell Script: Check Exchange 2010 Database Backups</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/powershell-html-email-formatting">How to Send SMTP Email Using PowerShell (Part 4)</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/powershell-html-email-formatting/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Win a Free PowerGUI Pro License</title>
		<link>http://exchangeserverpro.com/win-free-powergui-pro-license</link>
		<comments>http://exchangeserverpro.com/win-free-powergui-pro-license#comments</comments>
		<pubDate>Thu, 27 Oct 2011 11:54:57 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Contests]]></category>
		<category><![CDATA[PowerGUI]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Scripting]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4198</guid>
		<description><![CDATA[Find out how you can be in the running to win a free license of PowerGUI Pro, the leading PowerShell script editor from Quest Software.]]></description>
			<content:encoded><![CDATA[<p>Thanks to the folks at Quest Software I have one free license of <a href="http://www.quest.com/PowerGUIPro/">PowerGUI Pro</a> to give away.</p>
<p>I&#8217;ve tried a few different PowerShell editors and PowerGUI is the one I now use on a daily basis. From the PowerGUI website:</p>
<blockquote><p>PowerGUI® Pro is graphical PowerShell administration console with an integrated editor and debugger. PowerGUI Pro has all the same great features from our freeware PowerGUI, plus it enables use of PowerShell from mobile devices and protects your scripts with integrated version control.</p></blockquote>
<p>To be in the running to win this great prize all you have to do is write a PowerShell script to meet one (or more if you like) of the scripting challenges posted in the <a href="http://exchangeserverpro.com/forums/showthread.php?103-Win-a-Free-PowerGUI-Pro-License">Exchange Server Pro forums</a>.</p>
<p>There are three challenges:</p>
<ul>
<li>Top 12 Mailbox Size Report</li>
<li>Exchange Backups Check</li>
<li>Mailbox Statistics Report</li>
</ul>
<p>You can read the full details <a href="http://exchangeserverpro.com/forums/showthread.php?103-Win-a-Free-PowerGUI-Pro-License">here</a>.</p>
<p>The contest runs until midnight on Saturday 13th November (Australian EST) to allow plenty of time to create good quality scripts.</p>
<p>Best of luck!</p>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/test-mailflow-exchange-2003-servers" title="Using Test-Mailflow with Exchange 2003 Servers">Using Test-Mailflow with Exchange 2003 Servers</a></li><li><a href="http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email" title="How to Set Up an Automated Exchange 2010 Database Backup Alert Email">How to Set Up an Automated Exchange 2010 Database Backup Alert Email</a></li><li><a href="http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups" title="PowerShell Script: Check Exchange 2010 Database Backups">PowerShell Script: Check Exchange 2010 Database Backups</a></li><li><a href="http://exchangeserverpro.com/powershell-html-email-formatting" title="How to Send SMTP Email Using PowerShell (Part 4)">How to Send SMTP Email Using PowerShell (Part 4)</a></li><li><a href="http://exchangeserverpro.com/powershell-send-html-email" title="How to Send SMTP Email Using PowerShell (Part 3)">How to Send SMTP Email Using PowerShell (Part 3)</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/win-free-powergui-pro-license">Win a Free PowerGUI Pro License</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/win-free-powergui-pro-license/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Send SMTP Email Using PowerShell (Part 3)</title>
		<link>http://exchangeserverpro.com/powershell-send-html-email</link>
		<comments>http://exchangeserverpro.com/powershell-send-html-email#comments</comments>
		<pubDate>Mon, 24 Oct 2011 14:19:29 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Email]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[SMTP]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4191</guid>
		<description><![CDATA[Learn how to add HTML message body content to emails sent via PowerShell scripts.]]></description>
			<content:encoded><![CDATA[<p>In the last article in this series I showed you <a href="http://exchangeserverpro.com/powershell-email-message-body">how to add message body content to emails sent from PowerShell scripts</a>.</p>
<ul>
<li><a href="http://exchangeserverpro.com/powershell-how-to-send-email">Part 1 &#8211; How to Send SMTP Email Using PowerShell</a></li>
<li><a href="http://exchangeserverpro.com/powershell-email-message-body">Part 2 - How to Add a Message Body to Emails Sent from Scripts</a></li>
<li><strong>Part 3 - How to Add a HTML Message Body to Emails Sent from Scripts</strong></li>
<li><a href="http://exchangeserverpro.com/powershell-html-email-formatting">Part 4 - How to Create Formatted HTML Output from Scripts</a></li>
</ul>
<p>In this article we&#8217;ll take it a step further by adding a HTML message body to an email.</p>
<p>For this to work we&#8217;ll be using an <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage(v=VS.100).aspx">System.Net.Mail.MailMessage</a> .NET object. This is basically a message object that can be sent via the <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx">SmtpClient</a> .NET object that we used in the previous articles. The benefit of using this object in a script is that it can be used to create HTML email messages.</p>
<p>To create the script we can start with similar variables to last time.</p>
<pre>$smtpServer = "ho-ex2010-caht1.exchangeserverpro.net"
$smtpFrom = "reports@exchangeserverpro.net"
$smtpTo = "administrator@exchangeserverpro.net"
$messageSubject = "List of Exchange Servers"</pre>
<p>Next we create the new MailMessage object using the variables above as the To and From addresses, and then set the message subject as well.</p>
<pre>$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject</pre>
<p>Now comes the important bit, setting the message body to be HTML.</p>
<pre>$message.IsBodyHTML = $true</pre>
<p>Now all we need is some HTML content to go into the message body. As an example let&#8217;s just get a list of Exchange servers and their server roles.</p>
<pre>$message.Body = Get-ExchangeServer | Select-Object Name,ServerRole | ConvertTo-Html</pre>
<p>All I needed to do above is run <a href="http://technet.microsoft.com/en-us/library/bb123873.aspx">Get-ExchangeServer</a>, pipe the output into a <a href="http://technet.microsoft.com/en-us/library/dd315291.aspx">Select-Object</a> command to grab just the server name and roles, and then pipe that into the <a href="http://technet.microsoft.com/en-us/library/ee156817.aspx">ConvertTo-Html</a> command.</p>
<p>The final step is to create the SmtpClient object and send the mail message.</p>
<pre>$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)</pre>
<p>The result is an email that looks similar to this.</p>
<p><img class="aligncenter size-full wp-image-4192" title="powershell-send-html-email" src="http://exchangeserverpro.com/wp-content/uploads/2011/10/powershell-send-html-email.jpg" alt="" width="500" height="365" /></p>
<p>Here is the complete example script.</p>
<pre>$smtpServer = "ho-ex2010-caht1.exchangeserverpro.net"
$smtpFrom = "reports@exchangeserverpro.net"
$smtpTo = "administrator@exchangeserverpro.net"
$messageSubject = "List of Exchange Servers"

$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.IsBodyHTML = $true

$message.Body = Get-ExchangeServer | Select-Object Name,ServerRole | ConvertTo-Html

$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)</pre>
<p>As you can see this is a pretty simple technique that can be used to easily create basic HTML email messages.</p>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/powershell-email-message-body" title="How to Send SMTP Email Using PowerShell (Part 2)">How to Send SMTP Email Using PowerShell (Part 2)</a></li><li><a href="http://exchangeserverpro.com/powershell-html-email-formatting" title="How to Send SMTP Email Using PowerShell (Part 4)">How to Send SMTP Email Using PowerShell (Part 4)</a></li><li><a href="http://exchangeserverpro.com/powershell-how-to-send-email" title="How to Send SMTP Email Using PowerShell (Part 1)">How to Send SMTP Email Using PowerShell (Part 1)</a></li><li><a href="http://exchangeserverpro.com/test-mailflow-exchange-2003-servers" title="Using Test-Mailflow with Exchange 2003 Servers">Using Test-Mailflow with Exchange 2003 Servers</a></li><li><a href="http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email" title="How to Set Up an Automated Exchange 2010 Database Backup Alert Email">How to Set Up an Automated Exchange 2010 Database Backup Alert Email</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/powershell-send-html-email">How to Send SMTP Email Using PowerShell (Part 3)</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/powershell-send-html-email/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Test-ServiceHealth for Exchange Server Health Checks</title>
		<link>http://exchangeserverpro.com/exchange-2010-test-servicehealth</link>
		<comments>http://exchangeserverpro.com/exchange-2010-test-servicehealth#comments</comments>
		<pubDate>Tue, 18 Oct 2011 12:04:32 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[Features]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Diagnostics]]></category>
		<category><![CDATA[Exchange 2007]]></category>
		<category><![CDATA[Exchange 2010]]></category>
		<category><![CDATA[Exchange Management Shell]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Test-ServiceHealth]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4185</guid>
		<description><![CDATA[Learn how to build a PowerShell script that uses Test-ServiceHealth to perform health checks on your Exchange servers.]]></description>
			<content:encoded><![CDATA[<p><a href="http://exchangeserverpro.com">Exchange Server 2010</a> (and 2007 for that matter) ships with a useful PowerShell cmdlet called <a href="http://technet.microsoft.com/en-us/library/aa998852.aspx">Test-ServiceHealth</a>.</p>
<p>As the name suggests, Test-ServiceHealth checks the state of the services that should be running on the Exchange server. One of the best things about this cmdlet is that it checks the services depending on the <a href="http://exchangeserverpro.com/exchange-2010-server-roles">Exchange server roles</a> that are installed.</p>
<p>So for example, for a Hub Transport server only those services relating to the Hub Transport role will be checked. While for a &#8220;typical&#8221; Exchange 2010 server the services for the Hub Transport, Client Access, and Mailbox server roles will be checked.</p>
<p>Here is an example of the Test-ServiceHealth results.</p>
<pre>[PS] C:\&gt;Test-ServiceHealth br-ex2010-mb

Role                    : Mailbox Server Role
RequiredServicesRunning : True
ServicesRunning         : {IISAdmin, MSExchangeADTopology, MSExchangeIS, MSExchangeMailboxAssistants, MSExchangeMailSub
                          mission, MSExchangeRepl, MSExchangeRPC, MSExchangeSA, MSExchangeSearch, MSExchangeServiceHost
                          , MSExchangeThrottling, MSExchangeTransportLogSearch, W3Svc, WinRM}
ServicesNotRunning      : {}

Role                    : Client Access Server Role
RequiredServicesRunning : True
ServicesRunning         : {IISAdmin, MSExchangeAB, MSExchangeADTopology, MSExchangeFBA, MSExchangeFDS, MSExchangeMailbo
                          xReplication, MSExchangeProtectedServiceHost, MSExchangeRPC, MSExchangeServiceHost, W3Svc, Wi
                          nRM}
ServicesNotRunning      : {}

Role                    : Hub Transport Server Role
RequiredServicesRunning : True
ServicesRunning         : {IISAdmin, MSExchangeADTopology, MSExchangeEdgeSync, MSExchangeServiceHost, MSExchangeTranspo
                          rt, MSExchangeTransportLogSearch, W3Svc, WinRM}
ServicesNotRunning      : {}</pre>
<p>As you can see that is a lot of useful information. But whenever possible I like to see just the minimum relevant information for my servers. In the case of Test-ServiceHealth the RequiredServicesRunning result is the thing I am most interested in.</p>
<p>So in this case I could run the following command to see just that information:</p>
<pre>[PS] C:\&gt;Test-ServiceHealth br-ex2010-mb | ft Role,RequiredServicesRunning -auto

Role                      RequiredServicesRunning
----                      -----------------------
Mailbox Server Role                          True
Client Access Server Role                    True
Hub Transport Server Role                    True</pre>
<p>Much better.</p>
<p>Now suppose I wanted to run that for all of my Exchange servers. I could do that with the following command:</p>
<pre>[PS] C:\&gt;Get-ExchangeServer | Test-ServiceHealth | ft Role,RequiredServicesRunning -auto

Role                      RequiredServicesRunning
----                      -----------------------
Client Access Server Role                    True
Hub Transport Server Role                    True
Client Access Server Role                    True
Hub Transport Server Role                    True
Mailbox Server Role                         False
Mailbox Server Role                          True
Client Access Server Role                    True
Hub Transport Server Role                    True
Mailbox Server Role                          True
Client Access Server Role                    True
Hub Transport Server Role                    True</pre>
<p>Interesting, especially the one that failed the test for the Mailbox server role. But in that output I can&#8217;t tell which server failed.</p>
<p>Let&#8217;s try this instead:</p>
<pre>[PS] C:\&gt;$servers = Get-ExchangeServer
[PS] C:\&gt;foreach ($server in $servers) {
&gt;&gt; Write-Host "Checking" $server.name
&gt;&gt; Test-ServiceHealth $server | ft Role,RequiredServicesRunning -auto
&gt;&gt; }
&gt;&gt;</pre>
<p>Now we get output that is a little more useful, and tells me which server failed the test.</p>
<pre>Checking HO-EX2010-CAHT1

Role                      RequiredServicesRunning
----                      -----------------------
Client Access Server Role                    True
Hub Transport Server Role                    True

Checking HO-EX2010-CAHT2

Role                      RequiredServicesRunning
----                      -----------------------
Client Access Server Role                    True
Hub Transport Server Role                    True

Checking HO-EX2010-MB1

Role                RequiredServicesRunning
----                -----------------------
Mailbox Server Role                   False

Checking HO-EX2010-MB2

Role                RequiredServicesRunning
----                -----------------------
Mailbox Server Role                    True

Checking BR-EX2010-CAHT

Role                      RequiredServicesRunning
----                      -----------------------
Client Access Server Role                    True
Hub Transport Server Role                    True

Checking BR-EX2010-MB

Role                      RequiredServicesRunning
----                      -----------------------
Mailbox Server Role                          True
Client Access Server Role                    True
Hub Transport Server Role                    True</pre>
<p>But it still isn&#8217;t quite enough, so let&#8217;s wrap this up into a handy script that will do the following:</p>
<ul>
<li>Run Test-SystemHealth for all of the Exchange servers in the organization</li>
<li>Tell me which servers passed the test</li>
<li>Tell me which servers failed the test, and why</li>
</ul>
<p>Here is the script code that will perform those steps.</p>
<pre>#Get the list of Exchange servers in the organization
$servers = Get-ExchangeServer

#Loop through each server
ForEach ($server in $servers)
{
	Write-Host -ForegroundColor White "---------- Testing" $server

	#Initialize an array object for the Test-ServiceHealth results
	[array]$servicehealth = @()

	#Run Test-ServiceHealth
	$servicehealth = Test-ServiceHealth $server

	#Output the results
	ForEach($serverrole in $servicehealth)
	{
		If ($serverrole.RequiredServicesRunning -eq $true)
		{
			Write-Host $serverrole.Role -NoNewline; Write-Host -ForegroundColor Green "Pass"
		}
		Else
		{
			Write-Host $serverrole.Role -nonewline; Write-Host -ForegroundColor Red "Fail"
			[array]$notrunning = @()
			$notrunning = $serverrole.ServicesNotRunning
			ForEach ($svc in $notrunning)
			{
				$alertservices += $svc
			}
			Write-Host $serverrole.Role "Services not running:"
			ForEach ($al in $alertservices)
				{
					Write-Host -ForegroundColor Red `t$al
				}
		}
	}
}</pre>
<p>The output from running the script will look something like this.</p>
<p><img class="aligncenter size-full wp-image-4186" title="exchange-2010-test-servicehealth-script" src="http://exchangeserverpro.com/wp-content/uploads/2011/10/exchange-2010-test-servicehealth-script.jpg" alt="" width="539" height="267" /></p>
<p>You can now see at a glance which servers have passed the test, which ones failed, and which services aren&#8217;t running for the servers that failed.</p>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/migrate-relay-connector-exchange-server-2007-2010" title="How to Migrate a Relay Connector from Exchange Server 2007 to 2010">How to Migrate a Relay Connector from Exchange Server 2007 to 2010</a></li><li><a href="http://exchangeserverpro.com/list-users-access-exchange-mailboxes" title="How to List all Users Who Have Access to Other Exchange Mailboxes">How to List all Users Who Have Access to Other Exchange Mailboxes</a></li><li><a href="http://exchangeserverpro.com/clone-mailbox-database-configuration" title="Exchange 2007/2010: How to Clone a Mailbox Database Configuration">Exchange 2007/2010: How to Clone a Mailbox Database Configuration</a></li><li><a href="http://exchangeserverpro.com/exchange-2007-2010-public-folder-store-inconsistent-state" title="Exchange 2007/2010 Public Folder Store in an Inconsistent State">Exchange 2007/2010 Public Folder Store in an Inconsistent State</a></li><li><a href="http://exchangeserverpro.com/powershell-configuring-settings-multiple-exchange-mailbox-databases" title="PowerShell: Configuring Settings on Multiple Exchange Mailbox Databases">PowerShell: Configuring Settings on Multiple Exchange Mailbox Databases</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/exchange-2010-test-servicehealth">Using Test-ServiceHealth for Exchange Server Health Checks</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/exchange-2010-test-servicehealth/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Script to Create a Mailbox Size Report for Exchange Server 2010</title>
		<link>http://exchangeserverpro.com/powershell-script-create-mailbox-size-report-exchange-server-2010</link>
		<comments>http://exchangeserverpro.com/powershell-script-create-mailbox-size-report-exchange-server-2010#comments</comments>
		<pubDate>Sat, 15 Oct 2011 12:12:54 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[Solutions]]></category>
		<category><![CDATA[Exchange 2007]]></category>
		<category><![CDATA[Exchange 2010]]></category>
		<category><![CDATA[Mailboxes]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Reporting]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4170</guid>
		<description><![CDATA[This PowerShell script produces a nicely formatted mailbox size report for Exchange Server 2010 or 2007]]></description>
			<content:encoded><![CDATA[<p>One of the <a href="http://exchangeserverpro.com">Exchange Server</a> administration tasks I perform almost every day is creating mailbox size reports. There are a few different reasons that I create these reports, such as planning a mailbox migration project, responding to a storage capacity alert for a particular database, or providing a specific team of people with a report of their mailbox sizes.</p>
<p>Now it is pretty easy to <a href="http://exchangeserverpro.com/browsing-mailbox-databases-in-exchange-2007-and-2010">get the sizes for Exchange mailboxes</a> and to handle the formatting of the<a href="http://exchangeserverpro.com/calculate-exchange-2010-mailbox-sizes-powershell"> Exchange 2010 mailbox statistics</a> so that they are easier to perform calculations on, but it gets a bit boring running those commands day after day.</p>
<p>Even worse, after running the commands to create a CSV report I still had to open that in Excel, remove the unwanted details, use Excel formulas to convert the values from bytes to megabytes, sort them into order, and so on. Again not difficult, just boring after doing it hundreds of times.</p>
<p>So I created a <a href="http://exchangeserverpro.com/tag/powershell">PowerShell</a> script to do all of the heavy lifting for me, and I&#8217;m sharing that script with you here. Let&#8217;s take a look at how the script works.</p>
<p>Firstly the script accepts two optional parameters; <strong>-database</strong> or <strong>-file</strong>. These tell the script whether to run a report on a given mailbox database, or to run a report on a list of mailbox names in a text file.</p>
<pre>param(
	[string]$database = "",
	[string]$file = ""
)</pre>
<p>You can specify either parameter, but not both at once, nor can you run the script without any parameters.</p>
<pre>#Determine whether correct parameters have been used

if( $database -eq "" -and $file -eq "" )
{
	Write-Host -ForegroundColor Red "You must specify either -database or -file"
}

if( $database -ne "" -and $file -ne "" )
{
	Write-Host -ForegroundColor Red "You can't use both -database and -file"
}</pre>
<p>With the correct parameter used the script executes one of two functions to generate the report.</p>
<pre>#Get the report

if( $database -ne "" )
{
	Get-ReportDBMode $database
}

if( $file -ne "" )
{
	Get-ReportFileMode $file
}</pre>
<p>Those functions simply retrieve the mailbox statistics, sort them in order of largest to smallest, perform the conversions of the values from bytes to megabytes, and then clean up the output to just the relevant information.</p>
<pre>#...................................
# Functions
#...................................

function Get-ReportDBMode {

	param ($database)
	$report = Get-MailboxStatistics -database $database | Sort-Object TotalItemSize -Descending | Select-Object DisplayName,@{Label="Size(Mb)"; Expression={$_.TotalItemSize.Value.ToMb()}},LastLogonTime
	return ($report)
}

function Get-ReportFileMode {

	param ($file)
	$report = Get-Content $file | Get-MailboxStatistics | Sort-Object TotalItemSize -Descending | Select-Object DisplayName,@{Label="Size(Mb)"; Expression={$_.TotalItemSize.Value.ToMb()}},LastLogonTime
	return ($report)
}</pre>
<p>The output will be similar to this:</p>
<p><img class="aligncenter size-full wp-image-4171" title="powershell-mailbox-size-report" src="http://exchangeserverpro.com/wp-content/uploads/2011/10/powershell-mailbox-size-report.jpg" alt="" width="580" height="114" /></p>
<p>Here are a few examples of how to run the script:</p>
<pre>.\Get-MailboxReport.ps1 -database MB-HO-01

.\Get-MailboxReport.ps1 -file .\users.txt

.\Get-MailboxReport.ps1 -file .\users.txt | Export-CSV -NoTypeInformation -Path report.csv</pre>
<p>Here is the complete script:</p>
<pre>#Get-MailboxReport.ps1
#Written By: Paul Cunningham
#URL: http://exchangeserverpro.com
#
#Change Log
#V1.0, 15/10/2011 - Initial version
#
#.SYNOPSIS
#Lists the mailboxes and mailbox sizes for
#the specified database or list of users. Output
#is sorted by TotalItemSize in descending order.
#
#.EXAMPLE
#.\Get-MailboxReport.ps1 -database MB-HO-01
#Returns a report with the mailbox statistics for all mailbox users in
#database MB-HO-01
#
#.EXAMPLE
#.\Get-MailboxReport.ps1 -file .\users.txt
#Returns a report with the mailbox statistics for all mailbox users in
#the file users.txt
#
#.EXAMPLE
#.\Get-MailboxReport.ps1 -file .\users.txt | Export-CSV -NoTypeInformation -Path report.csv
#Exports the report into a CSV file so that it can be opened in Microsoft Excel for
#further analysis
#

param(
	[string]$database = "",
	[string]$file = ""
)

#...................................
# Static Variables
#...................................

#...................................
# Functions
#...................................

function Get-ReportDBMode {

	param ($database)
	$report = Get-MailboxStatistics -database $database | Sort-Object TotalItemSize -Descending | Select-Object DisplayName,@{Label="Size(Mb)"; Expression={$_.TotalItemSize.Value.ToMb()}},LastLogonTime
	return ($report)
}

function Get-ReportFileMode {

	param ($file)
	$report = Get-Content $file | Get-MailboxStatistics | Sort-Object TotalItemSize -Descending | Select-Object DisplayName,@{Label="Size(Mb)"; Expression={$_.TotalItemSize.Value.ToMb()}},LastLogonTime
	return ($report)
}

#...................................
# Script
#...................................

#Determine whether correct parameters have been used

if( $database -eq "" -and $file -eq "" )
{
	Write-Host -ForegroundColor Red "You must specify either -database or -file"
}

if( $database -ne "" -and $file -ne "" )
{
	Write-Host -ForegroundColor Red "You can't use both -database and -file"
}

#Get the report

if( $database -ne "" )
{
	Get-ReportDBMode $database
}

if( $file -ne "" )
{
	Get-ReportFileMode $file
}</pre>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/move-exchange-mailboxes-text-file-powershell" title="How to Move Exchange Mailboxes in a Text File using PowerShell">How to Move Exchange Mailboxes in a Text File using PowerShell</a></li><li><a href="http://exchangeserverpro.com/test-mailflow-exchange-2003-servers" title="Using Test-Mailflow with Exchange 2003 Servers">Using Test-Mailflow with Exchange 2003 Servers</a></li><li><a href="http://exchangeserverpro.com/powershell-script-check-exchange-2010-database-backups" title="PowerShell Script: Check Exchange 2010 Database Backups">PowerShell Script: Check Exchange 2010 Database Backups</a></li><li><a href="http://exchangeserverpro.com/exchange-2010-test-servicehealth" title="Using Test-ServiceHealth for Exchange Server Health Checks">Using Test-ServiceHealth for Exchange Server Health Checks</a></li><li><a href="http://exchangeserverpro.com/exchange-2010-online-mailbox-moves" title="Exchange 2010 FAQ: How to Minimise Downtime During Mailbox Migration from Exchange 2007">Exchange 2010 FAQ: How to Minimise Downtime During Mailbox Migration from Exchange 2007</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/powershell-script-create-mailbox-size-report-exchange-server-2010">PowerShell Script to Create a Mailbox Size Report for Exchange Server 2010</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/powershell-script-create-mailbox-size-report-exchange-server-2010/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to Send SMTP Email Using PowerShell (Part 2)</title>
		<link>http://exchangeserverpro.com/powershell-email-message-body</link>
		<comments>http://exchangeserverpro.com/powershell-email-message-body#comments</comments>
		<pubDate>Sun, 09 Oct 2011 12:30:15 +0000</pubDate>
		<dc:creator>Paul Cunningham</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Email]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Scripting]]></category>
		<category><![CDATA[SMTP]]></category>

		<guid isPermaLink="false">http://exchangeserverpro.com/?p=4161</guid>
		<description><![CDATA[Learn simple techniques for adding message body content to emails sent via PowerShell scripts.]]></description>
			<content:encoded><![CDATA[<p>In the last part of this series we looked at simple techniques for <a href="http://exchangeserverpro.com/powershell-how-to-send-email">sending email from PowerShell</a>.</p>
<ul>
<li><a href="http://exchangeserverpro.com/powershell-how-to-send-email">Part 1 &#8211; How to Send SMTP Email Using PowerShell</a></li>
<li><strong>Part 2 - How to Add a Message Body to Emails Sent from Scripts</strong></li>
<li><a href="http://exchangeserverpro.com/powershell-send-html-email">Part 3 - How to Add a HTML Message Body to Emails Sent from Scripts</a></li>
<li><a href="http://exchangeserverpro.com/powershell-html-email-formatting">Part 4 - How to Create Formatted HTML Output from Scripts</a></li>
</ul>
<p>In this article we&#8217;ll take a closer look at how you can create the email message body for emails that you are sending via PowerShell.</p>
<p>In the last article I demonstrated a simple PowerShell script for sending emails that contained the following code, using the <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx">SmtpClient</a> .NET object .</p>
<pre>#
#.SYNOPSIS
#Sends SMTP email via the Hub Transport server
#
#.EXAMPLE
#.\Send-Email.ps1 -To "administrator@exchangeserverpro.net" -Subject "Test email" -Body "This is a test"
#

param(
[string]$to,
[string]$subject,
[string]$body
)

$smtpServer = "ho-ex2010-caht1.exchangeserverpro.net"
$smtpFrom = "reports@exchangeserverpro.net"
$smtpTo = $to
$messageSubject = $subject
$messageBody = $body

$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)</pre>
<p>Now let&#8217;s build on that example by adding more content to the message body of the emails.</p>
<h2>Using Command Output as Email Message Content with PowerShell</h2>
<p>When running this script anything that we specify with the -Body parameter will be the message body of the email. It could be a text string, or it could even be the output from another PowerShell command. For example:</p>
<pre>[PS] C:\Scripts&gt;.\Send-Email.ps1 -To "administrator@exchangeserverpro.net" -Subject "List of Exchange Servers" -Body (Get-ExchangeServer)</pre>
<p>The command above would produce an email that looks like this:</p>
<p><img class="aligncenter size-full wp-image-4162" title="powershell-email-message-body-01" src="http://exchangeserverpro.com/wp-content/uploads/2011/10/powershell-email-message-body-01.jpg" alt="" width="580" height="239" /></p>
<p>Neat trick, but notice how the list of Exchange servers appears as all one string that wraps over two lines? Wouldn&#8217;t it be nicer to see the server names displayed in an easier to read list format? Let&#8217;s take a look at how you can achieve that.</p>
<pre>[PS] C:\Scripts&gt;[string]$emailbody = ""

[PS] C:\Scripts&gt;$servers = Get-ExchangeServer

[PS] C:\Scripts&gt;foreach ($server in $servers) {$emailbody = $emailbody + $server.name + "`r`n"}

[PS] C:\Scripts&gt;.\Send-Email.ps1 -To "administrator@exchangeserverpro.net" -Subject "List of Exchange Servers" -Body $emailbody</pre>
<p>So what did I do there? Here are the steps I just followed:</p>
<ol>
<li>Declare a variable <strong>$emailbody</strong> as type <strong>string</strong>. This will be the variable that is passed to the script to be the message body of the email that gets sent.</li>
<li>Used the <a href="http://technet.microsoft.com/en-us/library/bb123873.aspx">Get-ExchangeServer</a> cmdlet to retrieve a list of the Exchange servers in the organization into an array of <strong>$servers</strong>.</li>
<li>Looped through the array using the <a href="http://technet.microsoft.com/en-us/library/dd347608.aspx">ForEach-Object</a> (abbreviated to &#8220;foreach&#8221;) cmdlet and appended each server name to the $emailbody string, including (and this is the important part) a <strong>carriage return</strong> after each server name.</li>
<li>Ran the script using the $emailbody variable for the -Body script parameter.</li>
</ol>
<p>The result is an email that looks like this; much better don&#8217;t you agree?</p>
<p><img class="aligncenter size-full wp-image-4163" title="powershell-email-message-body-02" src="http://exchangeserverpro.com/wp-content/uploads/2011/10/powershell-email-message-body-02.jpg" alt="" width="580" height="302" /></p>
<p>Now this is only a demonstration. In reality you probably aren&#8217;t going to want to send yourself an email with a list of your Exchange servers, at least not very often.</p>
<p>However you can use the same techniques I&#8217;ve just demonstrated to build scripts that email you any command or script output, such as a <a href="http://exchangeserverpro.com/how-to-find-exchange-server-2010-mailboxes-without-storage-quotas">list of mailboxes with no storage quotas</a> that you have emailed to yourself automatically each month.</p>
<h2>Using File Contents as Email Message Content with PowerShell</h2>
<p>Another technique for getting content for the message body of an email sent via PowerShell is to use the contents of a file.</p>
<p>For example, I run continuous pings between certain servers to detect any network interruptions that may be occurring. An entry is written to a log file any time a ping times out. Every day I want to receive an email with the results of the previous day&#8217;s ping monitoring, so I can do that using a script like this.</p>
<pre>#
#.SYNOPSIS
#Sends daily dropped ping report
#
#.EXAMPLE
#.\Send-DroppedPingReport.ps1
#

$smtpServer = "ho-ex2010-caht1.exchangeserverpro.net"
$smtpFrom = "reports@exchangeserverpro.net"
$smtpTo = "administrator@exchangeserverpro.net"
$messageSubject = "Dropped ping report"

[string]$messagebody = ""

$logs = Get-Content C:\Logs\droppedpings.log

foreach ($log in $logs )
{
	$messagebody = $messagebody + $log + "`r`n"
}

$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)</pre>
<p>This is the same technique that was used earlier to create an array and loop through it to add the carriage returns so that the email is formatted nicely. The main difference is the use of <a href="http://technet.microsoft.com/en-us/library/ee176843.aspx">Get-Content</a> instead of Get-ExchangeServer.</p>
<p><img class="aligncenter size-full wp-image-4164" title="powershell-email-message-body-03" src="http://exchangeserverpro.com/wp-content/uploads/2011/10/powershell-email-message-body-03.jpg" alt="" width="580" height="254" /></p>
<p>As you can see it is very simple to create useful, informative emails that are sent by your PowerShell scripts.</p>
<h3  class="related_post_title">Related posts:</h3><ul class="related_post"><li><a href="http://exchangeserverpro.com/powershell-send-html-email" title="How to Send SMTP Email Using PowerShell (Part 3)">How to Send SMTP Email Using PowerShell (Part 3)</a></li><li><a href="http://exchangeserverpro.com/powershell-html-email-formatting" title="How to Send SMTP Email Using PowerShell (Part 4)">How to Send SMTP Email Using PowerShell (Part 4)</a></li><li><a href="http://exchangeserverpro.com/powershell-how-to-send-email" title="How to Send SMTP Email Using PowerShell (Part 1)">How to Send SMTP Email Using PowerShell (Part 1)</a></li><li><a href="http://exchangeserverpro.com/test-mailflow-exchange-2003-servers" title="Using Test-Mailflow with Exchange 2003 Servers">Using Test-Mailflow with Exchange 2003 Servers</a></li><li><a href="http://exchangeserverpro.com/set-automated-exchange-2010-database-backup-alert-email" title="How to Set Up an Automated Exchange 2010 Database Backup Alert Email">How to Set Up an Automated Exchange 2010 Database Backup Alert Email</a></li></ul><hr />
<p>This article <a href="http://exchangeserverpro.com/powershell-email-message-body">How to Send SMTP Email Using PowerShell (Part 2)</a> is © 2011 ExchangeServerPro.com</p>
<p>Get more <a href="http://exchangeserverpro.com">Exchange Server tips</a> at <a href="http://exchangeserverpro.com">ExchangeServerPro.com</a></p>]]></content:encoded>
			<wfw:commentRss>http://exchangeserverpro.com/powershell-email-message-body/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

