EWS Managed API Demo: Delete Items in Recycle Bin older than 30 days

Hallo zusammen,

Wo ich gerade schon dabei bin mit dem EWS Managed API herumzuspielen, habe ich mir einen lang ersehnten Wunsch erfüllt. Ich habe ein Powershell Script geschrieben, welches das Active Directory nach Mailboxen durchsucht und die Elemente im Outlook Papierkorb löscht, welche vor mehr als 30 Tagen zuletzt geändert wurden.

Disclaimer

Das Script habe ich selbst entwickelt und löscht Daten. Ausprobieren auf eigene Gefahr!

Und hier das Script - kann aber auch heruntergeladen werden.

###############################################################################
# EWS Delete Items in RecycleBin older than xx Days
# EWS Managed API DEMO
# Version 1.0 / 15.07.2012
# Andres Bohren / www.icewolf.ch / blog.icewolf.ch / info@icewolf.ch
###############################################################################


###############################################################################
# Function WriteLog
###############################################################################
Function WriteLog {
 PARAM (
 [string]$pLogtext
 )
 
    $pDate =  $(get-date -format "dd.MM.yyyy HH:mm:ss")
      
    $sw = new-object system.IO.StreamWriter($LogPath, 1)
    $sw.writeline($pDate + " " + $pLogtext)
    $sw.close()


}

###############################################################################
# Function Get-Mailboxes
###############################################################################
Function Get-Mailboxes
{
   

    Try {
 
            Write-Host ("Search for Mailboxes")
            WriteLog ("Search for Mailboxes")
           
           
            $pMailboxes = @()

   
            $Searcher = new-object System.DirectoryServices.DirectorySearcher
            $Searcher.PageSize = 1000
            $Searcher.SearchScope = "Subtree"
            $Searcher.Filter = "(&(&(ObjectClass=user)(msExchHomeServerName=*)(!msExchHideFromAddressLists=TRUE)))"
                      
            $SearchResult = $Searcher.FindAll()
           
            If ($SearchResult -ne $Null)
            {
           

                foreach ($Item in $SearchResult)
                {
                    $DirectoryEntry = $Item.GetDirectoryEntry()                 
                  
                    Write-Host ("ADObject: sAMAccountName=" + $DirectoryEntry.sAMAccountName + " / Mail=" + $DirectoryEntry.mail + " / DN=" + $DirectoryEntry.distinguishedName)
                    WriteLog ("ADObject: sAMAccountName=" + $DirectoryEntry.sAMAccountName + " / Mail=" + $DirectoryEntry.mail + " / DN=" + $DirectoryEntry.distinguishedName)
                   
                    $pMailboxes += $DirectoryEntry.mail
 
                }
               
                #DEBUG
                #Write-Host ("pGroupMember: " + $pGroupMember)
               
                Return ,$pMailboxes
               
            } else {
                Write-Host ("No Mailboxes found")
                WriteLog ("No Mailboxes found")
            }

           
    } catch [system.exception] {
        Write-Host ("Error in GetADGroupMember " + $_.Exception.ToString())
        WriteLog ("Error in GetADGroupMember " + $_.Exception.ToString())
    }

}

 

###############################################################################
# Function EmptyRecycleBin
# Deletes Items in Folder "Recycle Bin" older than xx Days
###############################################################################

Function EmptyRecycleBin {
    PARAM ([int]$pDaysToKeep)

    Try {
   
     
            #[Date]DeleteDate = DateAdd(DateInterval.Day, -30, get-date)
            [system.Datetime]$date = get-date
            [system.Datetime]$DeleteDate = $date.addDays(-$pDaysToKeep)
            Write-Host ("DeleteDate: " + $DeleteDate)

    
            $View = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000) 
            $ExResult = $EWService.FindItems([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::DeletedItems,$View)               

            If ($ExResult -ne $Null)           
                {
               
                Write-Host ("#Deleting Items in RecycleBin")
                WriteLog ("#Deleting Items in RecycleBin")

                Foreach ($Item In $ExResult.Items )
                    {
                   

                    #Delete of Older than xx Days
                    If ($Item.LastModifiedTime -lt $DeleteDate )
                        {
                        Write-Host ("DELETE THIS ITEM: subject=" + $Item.Subject + " LastModifiedTime=" + $Item.LastModifiedTime)
                        WriteLog ("DELETE THIS ITEM: subject=" + $Item.Subject + " LastModifiedTime=" + $Item.LastModifiedTime)
                        $Item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete)
                        }
                   
                    }
                }
   
     
    } catch [system.exception] {
        WriteLog ("Error in EmptyRecycleBin " + $_.Exception.ToString())
        Write-Host ("Error in EmptyRecycleBin " + $_.Exception.ToString())       
    }
}           

###############################################################################
# Function SendAdminMail
###############################################################################

Function SendAdminMail {

$AdminSubject = "EWS Cleanup RecycleBin Script"
$AdminBody = "See the Attachment with the Log of the Script"
$Attachment = new-object Net.Mail.Attachment($LogPath)

$message = New-Object system.net.mail.mailmessage ($AdminFrom,$AdminTo,$AdminSubject,$AdminBody)
$message.attachments.add($attachment)

$SmtpClient = new-object system.net.mail.smtpClient
$SmtpClient.host = $SmtpServer
$SmtpClient.Send($message)

}


###############################################################################
# MainProgramm
###############################################################################

# Global Vars
[string]$EwsApiDll = "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
[string]$LogPath = "T:\Visual Basic\PowerShell\EWSScript\EWSDeleteRecycleBin.log"

[string]$Email = "ewservice@icewolf.ch"
[string]$Username = "ewservice"
[string]$Password = "MySecredPassword!"
[string]$Domain = "Corp"
[string]$EWSURL = ""
#[string]$EWSURL = "https://icesrv01/EWS/Exchange.asmx"
#[string]$EWSURL = "https://icesrv01.corp.icewolf.ch/EWS/Exchange.asmx"

[int]$DaysToKeep = 30

[string]$SmtpServer = "172.21.175.11"
[string]$AdminFrom = "administrator@icewolf.ch"
[string]$AdminTo = "a.bohren@icewolf.ch"

 

# Main Programm

Try {
        WriteLog "###############################################################################"
        WriteLog "### Starting Script"
        WriteLog "###############################################################################"

        # Import EWS Managed API DLL
        Import-Module -Name $EwsApiDll
        Write-Host ("Imported EWS Module")
        WriteLog ("Imported EWS Module")

        # Connect to EWS
        #$EWService = ConnectEWS ($Email, $Username, $Password, $Domain, $EWSURL)
        # Create a new Exchange Service Object
        $EWService = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2)
        $EWService.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials($Username,$Password,$Domain)

        Write-Host ("Connecting to EWS...")
        WriteLog ("Connecting to EWS...")

        If ($EWSURL -eq "")
            {
                $EWService.AutodiscoverUrl($Email)
                Write-Host ("Using Autodiscover")
            } else {
                $EWService.Url = $EWSURL
                Write-Host ("Using EWS URL")
            }


        # Get Mailboxes
        $Mailboxes = Get-Mailboxes
       
        # For Each User Impersonate
        foreach ($Mailbox in $Mailboxes)
            {
                Write-Host ("-->Impersonation to Mailbox: " + $Mailbox)
                Writelog ("-->Impersonation to Mailbox: " + $Mailbox)
               
                $EWService.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $Mailbox)
           

                # Delete Items in Folder "Recycle Bin"
                EmptyRecycleBin ($DaysToKeep)
                 
           }


        # Clean Up
        WriteLog "###############################################################################"
        WriteLog "### Finished"
        WriteLog "###############################################################################"
        Write-Host "Finished"
       
        #Send Admin Mail
        Write-Host("Sending Admin Mail")
        SendAdminMail

    } catch [system.exception] {
        WriteLog ("Error in EmptyRecycleBin " + $_.Exception.ToString())
        Write-Host ("Error in EmptyRecycleBin " + $_.Exception.ToString())       
}

Und so siehts dann aus...

Und so sieht dann das Mail aus, welches der Admin erhält.

Grüsse
Andres Bohren