Working with Outlook using PowerShell

There was recently a request by an end user to have email items in a particular folder automatically deleted after they were older than X number of days. Right off I knew this could be done with the Outlook.Application com object, however I didn’t know exactly how. After a bit of digging and messing around I found that it could be done, and fairly easily at that.

The first step is establishing a variable and connecting it to the Outlook.Application com object like so.

$outlook = new-object -comobject “Outlook.Application”

You then need to establish a variable for the mapi namespace.

$mapi = $outlook.getnamespace(“mapi”)

At this point you’re essentially connected to the mailbox for Outlook. You can navigate through the objects in the mailbox by using GetDefaultFolder(), putting the appropriate number in the parenthesis. I’ve mapped out the default objects, listed below. Depending on your situation you might have more.

3 – Deleted Items
4 – Outbox5 – Sent Items
6 – Inbox
9 – Calendar
10 – Contacts
11 – Journal
12 – Notes
13 – Tasks
16 – Drafts
19 – Conflicts
20 – Sync Issues
21 – Local Failures
23 – Junk E-Mail
25 – RSS Feeds
28 – To-Do List
30 – Suggested Contacts

To connect to the Inbox folder, you would do:

$inbox = $mapi.GetDefaultFolder(6)

Now, connecting to a sub-folder doesn’t appear to be as straightforward as I thought it would be. So far the only way I’ve been able to connect to a sub-folder is by doing the following.

$subfolder = $inbox.Folders | Where-Object {$_.Name -eq “SubFolderName”}

You can then work with the sub-folder using the $subfolder variable. If you want to list all the items in the sub-folder, you can do:

$subfolder.items

If you’re only interested in items older than 1 day, you can do:

$date = (Get-Date).AddDays(-1)
$subfolder.items | Where-Object {$_.SentOn -lt $date}

Back to what I was trying to figure out, which is delete items in a folder that are X numbers of days old, you can delete items like so:

$date = (Get-Date).AddDays(-1)
$subfolder.items | Where-Object {$_.SentOn -lt $date} | ForEach-Object {$_.Delete()}

As I find more things worth mentioning that you can do with the Outlook com object I’ll be sure to add them.

Leave a Reply

Your email address will not be published. Required fields are marked *