#############################################################################
# Kill-Contacts.ps1
# Deletes any contact that hasn't been used in the last x days
#
# Pat Richard, Exchange MVP
# [URL unfurl="true"]http://www.ehloworld.com/[/URL]
#
# RIGHTS REQUIRED
# ===============
# Recipient admin
#
# UPDATES
# =======
# v1.1 - 12/09/2009 variable cleanup; event logging
# v1.0 – Original script
#
# Dedicated blog post:
#
# Future enhancements:
# Logging to eventlog
# Email notification of deleted contacts to HelpDesk
#
# DISCLAIMER
# ==========
# THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE
# RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
#############################################################################
if (-not((Get-PSSnapin) -match "Microsoft.Exchange.Management.PowerShell.Admin")){ Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin }
$strLogEachUser = $true
# option to surpress screen output
$strScriptName = $MyInvocation.MyCommand.Name
$evt = new-object System.Diagnostics.EventLog("Application")
$evt.Source = $strScriptName
$infoevent = [System.Diagnostics.EventLogEntryType]::Information
$strEventLogText = "Beginning processing."
$evt.WriteEntry($strEventLogText,$infoevent,70)
$OldestLogs = (Get-TransportServer $env:ComputerName).MessageTrackingLogMaxAge.Days
$Start = (Get-Date).AddDays(-$OldestLogs)
$total2bwacked = 0
$Contacts = Get-Contact | Sort-Object DisplayName
cls
% ($contact in $contacts){
write-host "Checking " $contact.DisplayName " ("$contact.WindowsEmailAddress") " -nonewline
$mylog = @(Get-MessageTrackingLog -Eventid receive -Recipients $contact.WindowsEmailAddress -start $start)
if ($mylog.length -eq 0){
Write-Host $mylog.length -foregroundcolor red
Remove-MailContact $contact.displayname -whatif
if($strLogEachUser){
$strEventLogText = "Contact deleted for $Contact.DisplayName ($Contact.WindowsEmailAddress)"
$evt.WriteEntry($strEventLogText,$infoevent,70)
}
$total2bwacked++
}else{
Write-Host $mylog.length -foregroundcolor green
}
}
write-host "Total: $total2bwacked"
# notify HelpDesk
$strEventLogText = "Finished processing $total2bwhacked contacts."
$evt.WriteEntry($strEventLogText,$infoevent,70)