Monday, September 24, 2012

Message Tracking in Exchange 2007 & Exchange 2010 + powershell script

#add the below line for exchange 2007  & if you want to schedule the job with windows task scheduler. otherwise you can ignore it
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
# Control variables
$subject=" Failed mails report - " + (Get-Date -format F) + " PST"

#Prepare target file name based on current date pattern, to second granularity
$date=Get-Date -format yyyy-MMM-dd-HH-mm-ss
$targetfile = "D:\Mailfail\MessageTrack" + $date + ".csv"

# Create start and end date for parsing the mail-log files
# Startdate is always relative to current date, 1 day back
# Enddate is now()
$today = get-date
$rundate = $($today.adddays(-$daystoparse)).toshortdatestring()
$startdate = $rundate + " " + $today.Hour + ":" + $today.Minute + ":" + $today.Second + " AM"
$enddate = Get-Date -format G

get-messagetrackinglog -ResultSize Unlimited -EventID "FAIL" -Start $startdate -End $enddate | select timestamp, eventid, source,messagesubject, sender, {$_.recipients},clientip, clienthostname, serverip, serverhostname, connectorid, {$_.recipientstatus}, totalbytes, recipientcount, relatedrecipientaddress, returnpath | export-csv $targetfile

$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $from
$msg.Subject = $subject
$msg.Body = $body
$att = New-Object Net.Mail.Attachment($targetfile)

save the above script as by any name e.g messageTrack.ps1 and schedule it via windows job scheduler.

for that create a bat file e.g schedule.bat and put the below line.

Powershell.exe -command "& {d:\scripts\messageTrack.ps1}"

It is important to note that if you are running Exchange based scripts from the Windows Command prompt by passing them as a parameter to Powershell.exe you should add the following line at the top of each script:

For Exchange 2007

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin

For Exchange 2010
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

It will send one day report (mail fail) (or any other based on the argument you set) to the email id you choose.

If you want to send the email to multiple users then  add the users one by one and separate them by comma



- Exchange 2007 message tracking
- Message Tracking in exchange 2007
- How to track messages in exchange 2007
- Exchange 2007 message tracking attachment
-create message tracking in exchange 2007 and send them as attachment
-Exchange 2007 Script: how to run as a scheduled task

No comments:

Post a Comment