PleaseHelpTheNewGuy
PleaseHelpTheNewGuy

Reputation: 177

How to specify a subfolder of Inbox using Powershell

I'm trying to access a subfolder of "Inbox" named "subfolder" in outlook (2010) using Powershell.

$olFolderInbox = 6
$outlook = new-object -com outlook.application;
$ns = $outlook.GetNameSpace("MAPI");
$inbox = $ns.GetDefaultFolder($olFolderInbox)

# how do I specify a subfolder that's inside Inbox???
# I mean, "Inbox\subfolder" where "subfolder" is the name of the subfolder...

How do I specify this subfolder?

I'm sure this is really simple, which is why I am about to "lose it." Thanks in advance!

*Later in my code, I search the body for a "searchterm" and send the results to a text file if there's a match. The following code works for my Inbox:

$inbox.items | foreach {
if($_.body -match "searchterm") {$_.body | out-file -encoding ASCII foo.txt} # prints to file...

Instead of the inbox, I want to look at the subfolder of inbox as described above...

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

EDIT:

$olFolderInbox = 6
$outlook = new-object -com outlook.application;
$ns = $outlook.GetNameSpace("MAPI");
$inbox = $ns.GetDefaultFolder($olFolderInbox)
$targetfolder = $inbox.Folders | where-object { $_.name -eq "Subfolder" }
$targetfolder.items | foreach {
if($_.body -match "keyword") {$_.body | out-file -Append -encoding ASCII foo.txt} # keyword match prints body to file...
}

OK, I think this works now...

I don't know what I was doing wrong, although it's literally my first day using Powershell, so it's no surprise, really.

Upvotes: 0

Views: 18885

Answers (2)

Daniel Richnak
Daniel Richnak

Reputation: 1604

$targetfolder = $inbox.Folders | where-object { $_.name -eq "subfolder" }
$targetfolder.items | where-object { $_.body -match "keyword" } | % { $_.body } # can then redirect the body to file etc.

EDIT: not sure why your newest edit wouldn't work. Yours looks to be similar in construction to the one I have above, which I verified against my own mailbox.

EDIT EDIT: Be sure that if you're using out-file, you append the results rather than overwriting with each match.

Upvotes: 5

user189198
user189198

Reputation:

Try using the Where-Object cmdlet to filter the Folders returned from $inbox.Folders.

$Subfolder = $inbox.Folders | Where-Object -FilterScript { (Split-Path -Path $_.FolderPath -Leaf) -eq 'Subfolder' }

Here is an alternative / short-hand version of the above. This won't be quite as reliable, since you could have another folder called MySubfolder that's distinct from Subfolder.

$Subfolder = $inbox.Folders | ? { $_.FolderPath.EndsWith('Subfolder') }

Upvotes: 1

Related Questions