Script – Mailbox Audit

This is a script I wrote that will look for specific email accounts in an OU, and then send an email to all the people who have access to those email accounts.

#$ErrorActionPreference = "SilentlyContinue"
 $smtpServer = "[REMOVED]"
 $smtp = new-object Net.Mail.SmtpClient($smtpServer)
 $emailFrom = "mkieffer@[REMOVED]"

$a = get-user -OrganizationalUnit "[REMOVED]/Corp/Email Accounts" | where {$_.DistinguishedName -notlike '*OU=Contacts,OU=Email Accounts,OU=[REMOVED]' -and $_.DistinguishedName -notlike '*OU=Resources,OU=Email Accounts,OU=[REMOVED]'} | sort name

foreach ($item in $a) {

$mailboxName = $
 $mailboxAddress = $item.WindowsEmailAddress
 $body = "We are in the process of auditing access rights to shared mailboxes. According to our audit, you have access to the mailbox ""$mailboxName"".

 $smtpAddresses = get-mailbox $mailboxName | select -expand EmailAddresses | %{$_.SmtpAddress}
 $body += "This mailbox has the following email addresses:

Primary Contact: [None Specified]

 $body += "The Following employees have full access to this mailbox:`r`n"
 $subject = ""
 $emailTo = "mkieffer@[REMOVED]"
 $subject = "Audit of mailbox $mailboxName ($mailboxAddress)"
 echo "$mailboxName ($mailboxAddress)"
 $b = get-mailboxpermission $item.Name | where {$_.AccessRights -like "*FullAccess*"}
 $newEmailTo = ""
 $emailcounter = 0
 foreach ($item2 in $b) {
 [String]$name = $item2.User
 $c = get-mailbox $name
 if ($c.OrganizationalUnit -eq "[REMOVED]/Corp/Users/Employees" -and $ -ne "Mike Kieffer" ) {
 [String]$email = $c.WindowsEmailAddress
 [String]$fname = $c.DisplayName
 echo "--> $fname ($email)"
 $body += $fname
 $body += [char]13
 if ($emailcounter -gt 0) {$newEmailTo += ", "}
 $newEmailTo += $email
 $emailcounter = $emailcounter + 1
 $body += "`r`nPlease reply to this email with the following information:
 1- If this mailbox is still needed or if this mailbox can be deleted.
 2- Who is the primary contact for this mailbox.
 3- Who needs to be added or removed from accessing this mailbox.
 4- If any of the email addresses associated with this mailbox are no longer used, and can be removed.
 5- Is the name of ""$mailboxName"" still approrpiate for this mailbox.

 Mike Kieffer
 IT Sr. Systems Administrator
 echo $subject
 echo $body
 echo $newEmailTo
 $smtp.Send($emailFrom, $newEmailTo, $subject, $body)

Of course, you will need to modify the script to work in your environment, but this is a good starting point.  Suggestions are welcomed on how to increase the usability of this script and also the effectiveness of it.

If you are unable to delete some of the users from the mailboxes during the audit, you may find this post helpful: Cannot remove ACE on object…