The recursive selection of directories from Outlook

by Feb 8, 2012

Hi All.

I have found how to receive the list of directories from Outlook here. I have wanted to rewrite this code more compactly and have made it so:

function get-mailfolders {            
    $outlookfolders = @()
    $outlook = New-Object -ComObject Outlook.Application
    $outlook.Session.Folders | ForEach-Object {$_.Folders} | 
    ForEach-Object {$outlookfolders += New-Object PSObject -Property @{            
        Path = $($_.FullFolderPath)= $($_.EntryID)= $($_.StoreID)}            
    }
    $outlookfolders       
}

The result turns out identical, but in both cases there is a problem: nested directories aren't considered. I have changed the code so:

function get-mailfolders2 {            
    $outlookfolders = @()
    $outlook = New-Object -ComObject Outlook.Application
    $outlook.Session.Folders | ForEach-Object {$_.Folders} | ForEach-Object { $outlookfolders += get-subfolders $_ }
    $outlookfolders       
}
# The recursive handling  function get-subfolders ($folder) { $array = New-Object PSObject -Property @{ Path = $($folder.FullFolderPath)= $($folder.EntryID)= $($folder.StoreID)} $folder.Folders | ForEach-Object $array += get-subfolders $_ }
$array
}

I run it:

get-mailfolders2 | Select-Object -Property Path

But I get error message:

Error at performance of a script because of overflow of depth of calls. Depth of a call has reached 1001 And the maximum value 1000. At line:0 char:0

Where my error? In get-subfolders function, for $folder.Folders property, I receive empty value always. Why?

Regards