Outlook - Moving subfolders with e-mails from Inbox folder to .pst file using Powershell

Hi All,

I would like to move the subfolders of the Old folder under the Inbox folder and its contents into a pst file, so far without success.

Can you help me out?

Thanks

$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNamespace("MAPI")

$Mailbox = "xx@yy.com"
$SourceFolderName = "Old"
$TargetPSTPath = "C:\Users\xy\Desktop\backup.pst"  
$TargetFolderName = "Inbox"

$MailboxFolder = $Namespace.Folders | Where-Object { $_.Name -eq $Mailbox }
$SourceFolder = $MailboxFolder.Folders.Item("Inbox").Folders.Item($SourceFolderName)

$TargetPST = $Namespace.AddStore($TargetPSTPath)
$TargetFolder = $TargetPST.GetRootFolder().Folders.Item($TargetFolderName)

if ($SourceFolder -and $TargetFolder) {
    $SourceSubFolders = $SourceFolder.Folders
    foreach ($SubFolder in $SourceSubFolders) {
        $NewFolder = $TargetFolder.Folders.Add($SubFolder.Name)
        $SubFolderItems = $SubFolder.Items
        $ItemCount = $SubFolderItems.Count
        for ($i = $ItemCount; $i -gt 0; $i--) {
            $Item = $SubFolderItems.Item($i)
            $Item.Move($NewFolder)
        }
        $SubFolder.Delete()
    }
}
else {
    Write-Host "Not found"
}

$TargetPST.Remove()

No way for me to test … Indexing starts at 0, so you will miss the entry. Might want to change to:

$i -ge 0

Hi Szivesen, welcome to the forum!

“without success” doesn’t tell us a thing about what happens. Do you get errors? Does anything happen? Please keep in mind we can’t see your screen nor read your mind. :slight_smile:

1 Like