A Script To Delete ALL Of The Attachments In ALL Of Your Exchange Server Mailboxes (use with care!)

Leave a comment

(Edit) If you want a script to delete the attachments in a single mailbox, go here. If you really are looking for the nuclear option, read on…

Did you ever want to just delete all of the attachments in all of your mailboxes?  Okay, probably not.  But today, someone in one of the MS Technet Forums asked just that.  Maybe they were desperate to get some disk space back (remember to offline defrag afterwards)?  Who knows?  But it can be done.  Save all the text below to a .ps1 file, and run it as a script in PowerShell.  Don’t come crying to me if you do this without CAREFULLY THINKING ABOUT IT FIRST!  If you’re interested in trying it, let me know.  There are a couple of assumptions made that you may not be able to work out for yourself.

Import-Module -Name "C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll"
$credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials(ADMINUSERNAME, PASSWORD)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
$service.Credentials = $credentials
$service.Url = "https://localhost/ews/exchange.asmx"
$mailboxes = Get-Mailbox -ResultSize Unlimited
$folderFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter
$folderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)
$folderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep
$itemFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.EmailMessageSchema]::HasAttachments, $true)
$itemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(10000)
foreach ($mailbox in $mailboxes)
write-host $mailbox.displayName
$folderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot, $mailbox.primarySmtpAddress.ToString())
$folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $folderId)
$folders = $service.FindFolders($folderId, $folderFilter, $folderView)
foreach ($subFolder in $folders.Folders)
write-host $subFolder.displayName
$items = $subFolder.FindItems($itemFilter, $itemView)
foreach ($item in $items.Items)
write-host $item.subject
foreach($attachment in $item.Attachments)
write-host $attachment.Name

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>