How to Manage COMObject while Listing all folders in Outlook

16 Views Asked by At

I've crafted a PowerShell script to list all folders (and sub folders) in Outlook on my PC. The challenge that I am having is that instead of listing folders, the string is being spammed

$ (System.__ComObject.FolderPath) - $ (System.__ComObject.FolderPath)
    $ (System.__ComObject.FolderPath) - $ (System.__ComObject.FolderPath)
    $ (System.__ComObject.FolderPath) - $ (System.__ComObject.FolderPath)
    $ (System.__ComObject.FolderPath) - $ (System.__ComObject.FolderPath)

The following is the script developed to list all the folders in Outlook

# Clear the console
cls

# Add the Outlook COM Object
Add-Type -AssemblyName "Microsoft.Office.Interop.Outlook"

# Create an instance of the Outlook Application
$outlook =  New-Object -ComObject Outlook.Application

# Get root folder of Outlook
$rootFolder = $outlook.Session.DefaultStore.GetRootFolder()

# List the folders
function ListFolders($folder, $indentLevel) {
    $indent = " " * $indentLevel 
    Write-Host "$indent$ ($folder.FolderPath) - $ ($folder.FolderPath)"

    foreach ($subFolder in $folder.Folders) {
    ListFolders $subFolder ($indentLevel + 2)
    }
}

# Call the function to list all folders
ListFolders $rootFolder 0

# Release COM Objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($rootFolder) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($outlook) | Out-Null

# Clean Up
Remove-Variable outlook, rootFolder
0

There are 0 best solutions below