Use PowerShell to Move, Delete and Measure Outlook Emails

I know and like PowerShell. You know the old adage, when you have a hammer, hit outlook with the hammer.

####
# Connect to outlook


$Outlook = New-Object -ComObject Outlook.Application


####

# Old inbox to PST archive


$EmailToMove = $Outlook.Session.Folders.Item(1).Folders.Item("Inbox").Items | Where-Object SentOn -le (Get-date).AddDays(-30)


$EmailToMove | ft SentOn, Subject, SenderName, To, Sensitivity -AutoSize -Wrap


$ArchiveFolder = $Outlook.Session.Folders.Item(3).Folders.Item("Inbox")


FOREACH($Email in $EmailToMove )
    {
    $Email.Move($ArchiveFolder)

}

####
# Old sent to PST archive
$EmailToMove = $Outlook.Session.Folders.Item(1).Folders.Item("Sent Items") | Where-Object SentOn -le (Get-date).AddDays(-30)
$EmailToMove | ft SentOn, Subject, SenderName, To, Sensitivity -AutoSize -Wrap
$ArchiveFolder = $Outlook.Session.Folders.Item(3).Folders.Item("Sent")
FOREACH($Email in $EmailToMove )
    {
    $Email.Move($ArchiveFolder)
}

####
# Measure outlook folder sizes
$Folders = $Outlook.Session.Folders.Item(1).Folders
$ItemSizes = 0
FOREACH($Folder in $Folders )
    {
    FOREACH($Item in $Folder.Items )
        {
        $ItemSizes = $Item.size
    }
    $Folder.name
    ($ItemSizes | measure-object -sum).sum
    $ItemSizes = 0

}


####
# Delete alert folder emails
$EmailsInFolderToDelete = $Outlook.Session.Folders.Item(1).Folders.Item("Inbox").Folders.Item("alert").Items
foreach ($email in $EmailsInFolderToDelete)
    {
    $email.Delete()
}

Big thank you to sqlnotesfromtheunderground.wordpress.com for getting me started with using powershell to work with outlook.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s