'Get all subfolders of a specific public folder

I want to get all subfolders of a specific public subfolder.

The problem I face is that "Deep traversal queries are not allowed on public folders." so I am a bit lost at how to do that now.

Here is my code:

Function FindAllSubfolders(){
    $tfTargetidRoot = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::PublicFoldersRoot)
    $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$tfTargetidRoot)

    $FolderPath = "/mydomain.com/parentfolder"
    $pfArray = $FolderPath.Split("/")
    for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
        $pfArray[$lint]
        $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
        $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$pfArray[$lint])
        $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)
        if ($findFolderResults.TotalCount -gt 0){
            foreach($folder in $findFolderResults.Folders){
                $tfTargetFolder = $folder               
            }
        }
    }
    
    $folderview = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10000)
    $folderview.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.Webservices.Data.BasePropertySet]::FirstClassProperties)
    $folderview.PropertySet.Add([Microsoft.Exchange.Webservices.Data.FolderSchema]::DisplayName)
    $folderview.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
    $folderfindResults = $service.FindFolders($tfTargetFolder.id, $folderview)
    return $folderfindResults
}


Solution 1:[1]

Untested, but you can try this:

$result = Get-PublicFolder -Identity "/mydomain.com/parentfolder" -Recurse -ResultSize Unlimited -ErrorAction SilentlyContinue | ForEach-Object {
    [PsCustomObject]@{            
        FolderPath   = $_.Identity
        DisplayName  = $_.DisplayName
        EmailAddress = if ($_.MailEnabled) {$_.PrimarySmtpAddress.ToLower()} else {$null}
    }
}

# show the results
$result | Format-Table -AutoSize  # or Out-GridView if you prefer

# save as CSV file
$result | Export-Csv -Path 'X:\path\to\PublicFolders.csv' -NoTypeInformation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Theo