Tracking E-mail on Exchange With Powershell

Standard

I had a problem with the delivery of e-mails. The script presented below creates an Excel document with all the e-mails send from a specific e-mail address with the event.

The script takes four arguments:

  1. AddressList
  2. StartDate
  3. EndDate
  4. Output

AddressList

The address list is a mandatory parameter containing the full path to the text file contacining the e-mail adresses.

The file is formatted as follows:

Email
user01@domain1.com
user02@domain2.com

StartDate

The start date is the date from when the list is generated. The start date is not mandatory. If no parameter is given the standard start date is seven days from the day the script is executed.

EndDate

The end date is the date at which the list ends. The end date is not mandatory. If no parameter is given the standard end date is the day the script is executed.

Output

This parameter is full path to a directory where the files need to be saved. The parameter is not mandatory. If no paremeter is given the script will open a new Excel document for each e-mail address present in the source file.

The script outputs an Excel document containing e-mail information with the columns: Timestamp, Sender, Receiver, Event.

Usage
Without the start date and end date

Get-MessageTracking.ps1 -AddressList 'c:\addresses.txt' -Output 'c:\output'

With the start date and end date

Get-MessageTracking.ps1 -AddressList 'c:\addresses.txt' -StartDate '24/01/2011' -EndDate '31/01/2011' -Output 'c:\output'

The Code

# PowerShell script to get messagetracking of an e-mail address
#
# Author: Sander Stad
# Version: 1.1 Januari 2011 tested on Powershell v2.0
#
# Changes:
# Version 1.0:
# Initial version worked as it should
# Version 1.1:
# Implementation of parameters
# Implementation of constants
# Error check on parameters
# Implemented output to Excell file on disk
#
# Usage:
# .\Get-MessageTracking.ps1 -AddressList 'c:\addresses.txt' -Output 'c:\output'

Param(
[Parameter(position=1,Mandatory = $true )][string] $AddressList, # List of servers that needs to be checked. Has to a text file!
[Parameter(position=2,Mandatory = $false )][string] $StartDate, # Start date for the querie
[Parameter(position=2,Mandatory = $false )][string] $EndDate, # End date for the querie
[Parameter(position=2,Mandatory = $false )][string] $Output # Output directory for the Excell file. If no value is given an Excell sheet will open.

)

Process
{
# Set constant variables
Set-Variable -Name _DATESTART -Option Constant -Value (Get-Date).Adddays(-7)
Set-Variable -Name _DATEEND -Option Constant -Value (Get-Date)
Set-Variable -Name _WAITTIME -Option Constant -Value 2

CLS

# Set global error check
# Value 1: High error program will stop
# Value 2: Warning program will continue
# Value 3: Information about execution
$ErrorStatus = 0;

#Set Excel activity
# Value 1: Excell sheet will open on execute (Default value)
# Value 2: Excell sheet will be written to given path
$ExcelAction = 0;

If($Output -eq '')
{
Write-Host "INFO: Path for output not given. Excell sheet will be opened." -ForegroundColor Red -BackgroundColor Green
$ExcelAction = 1
$ErrorStatus = 3
}
ElseIf(Test-Path $Output)
{
Write-Host "INFO: Excell sheet will be opened written to $Output." -ForegroundColor Red -BackgroundColor Green
$ExcelAction = 2
$ErrorStatus = 3
}
Else
{
Write-Host "INFO: Path for output is set. Data will be written to $Output." -ForegroundColor Red -BackgroundColor Green
$ExcelAction = 2
$ErrorStatus = 3
}
# Check all the parameters
If($AddressList -eq '')
{
Write-Host "ERROR: Server list not given" -ForegroundColor Red -BackgroundColor Yellow
$ErrorStatus = 1
}
ElseIf(!(Test-Path $AddressList))
{
Write-Host "ERROR: Path to serverlist doesn't exist" -ForegroundColor Red -BackgroundColor Yellow
$ErrorStatus = 1
}
If($StartDate -eq '')
{
$dateStart = (Get-Date).Adddays(-7)
Write-Host "INFO: Start date is not given. Start date is set to: $dateStart." -ForegroundColor Red -BackgroundColor Green
$ExcelAction = 2
$ErrorStatus = 3

}
Else
{
$dateStart = $StartDate
}
If($EndDate -eq '')
{
$dateEnd = (Get-Date)
Write-Host "INFO: End date is not given. End date is set to: $dateEnd." -ForegroundColor Red -BackgroundColor Green
$ExcelAction = 2
$ErrorStatus = 3
}
Else
{
$dateEnd = $EndDate
}
# Check if any error occured in the parameters
If($ErrorStatus -eq 0)
{
Write-Host ""
Write-Host "No errors found in the parameters. Continuing....." -ForegroundColor Green
Start-Sleep -Seconds $_WAITTIME
}
ElseIf($ErrorStatus -eq 1)
{
Write-Host ""
Write-Host "Critical errors found. Exiting..." -ForegroundColor Red
Start-Sleep -Seconds $_WAITTIME
Exit
}
ElseIf($ErrorStatus -eq 2)
{
Write-Host ""
Write-Host "Warnings found in the parameters. Continuing....." -ForegroundColor Blue
Start-Sleep -Seconds $_WAITTIME
}
ElseIf($ErrorStatus -eq 3)
{
Write-Host ""
Write-Host "Informational messages found. Continuing....." -ForegroundColor Green
Start-Sleep -Seconds $_WAITTIME
}

#Get all the adresses
$addresses = Import-Csv $AddressList

#Read through the contents of the source file
Foreach($address In $addresses)
{

# Set the settings for the Excel sheet
If($ExcelAction -eq 1)
{
#Create a new Excel object using COM
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)
}
ElseIf($ExcelAction -eq 2)
{
#Create a new Excel object using COM
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $False
#$Excel = $Excel.Workbooks.Open()
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)

}

#Counter variable for rows
$intRow = 1

$Sheet.Cells.Item($intRow,1) = "TIMESTAMP"
$Sheet.Cells.Item($intRow,2) = "SENDER"
$Sheet.Cells.Item($intRow,3) = "RECIPIENTS"
$Sheet.Cells.Item($intRow,4) = "EVENT"

#Format the column headers
For ($col = 1; $col –le 4; $col++)
{
$Sheet.Cells.Item($intRow,$col).Font.Bold = $True
$Sheet.Cells.Item($intRow,$col).Interior.ColorIndex = 48
$Sheet.Cells.Item($intRow,$col).Font.ColorIndex = 34
}

#Increase the row number
$intRow++

#Get the e-mail addres from the list
$emailAddress = $address.Email

#Get the results
$results = Get-TransportServer | Get-MessageTrackingLog -Sender $emailAddress -Start $_DATESTART -End $_DATEEND | Select-Object Timestamp, Sender, Recipients, EventId | sort Timestamp

Foreach($result In $results)
{
#Write-Host $result.Timestamp ',' $result.Sender ',' $result.Recipients ',' $result.EventId

# Insert the values
$Sheet.Cells.Item($intRow, 1) = $result.Timestamp
$Sheet.Cells.Item($intRow, 2) = $result.Sender
$Sheet.Cells.Item($intRow, 3) = $result.Recipients
$Sheet.Cells.Item($intRow, 4) = $result.EventId

# Increment the row number
$intRow ++
}

# Increment the row number
$intRow ++

# Transform the email address for a valid file name
$at = $emailAddress.IndexOf("@")
$filename = $emailAddress.ToLower().Replace(".", "_").Substring(0, $at)
$destination = $Output + "\$filename"

# Automatically size the field in the excel sheet
$Sheet.UsedRange.EntireColumn.AutoFit()

# Close the document if it's automatically written to disk
If($ExcelAction -eq 2)
{
$Excel.SaveAs($destination, 56)
$Excel.Close($False)
}
}
}