-
-
Save junecastillote/93cd6d6355fab595b7185f27e3e4e20d to your computer and use it in GitHub Desktop.
Export Public Folder to PST with PowerShell and Outlook COM Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory)] | |
[string] | |
$PublicFolderPath, | |
[Parameter(Mandatory)] | |
[string] | |
$PstFilePath | |
) | |
## Initialize the Outlook COM Object | |
$Outlook = New-Object -ComObject Outlook.Application | |
## Compose the top public folder path <Public Folders - ACCOUNT_NAME\All Public Folders> | |
$pfTopFolder = $Outlook.Session.Folders | Where-Object { $_.Name -like "Public Folders -*" } | |
## Append the specified $PublicFolderPath | |
$PublicFolderPath = (($pfTopFolder.Name) + '\All Public Folders\' + $PublicFolderPath) | |
Write-Verbose "Public Folder Parent = $PublicFolderPath" | |
## Split the folder path into levels | |
$pfPath = $PublicFolderPath.Split('\') | |
## Initialize the public folder object to export. | |
$PublicFolderToExport = $Outlook.Session.Folders.Item($pfPath[0]).Folders.Item($pfPath[1]) | |
## Append each public folder level | |
for ($i = 2; $i -lt ($pfPath.count); $i++) { | |
try { | |
$PublicFolderToExport = $PublicFolderToExport.Folders.Item($pfPath[$i]) | |
} | |
catch { | |
## If the folder name does not exist, terminate the script. | |
"The public folder path [$($PublicFolderPath)] does not exist." | Out-Default | |
return $null | |
} | |
} | |
Write-Verbose $($PublicFolderToExport.FullFolderPath) | |
## Create the PST export folder if it doesn't exist. | |
$pstFolder = Split-Path $PstFilePath -Parent | |
if (!(Test-Path $pstFolder)) { | |
try { | |
$null = New-Item -Type Directory -Path $pstFolder -ErrorAction Stop | |
Write-Verbose "Output folder [$pstFolder] created." | |
} | |
catch { | |
Write-Error "Failed to create the folder [$pstFolder]." | |
Write-Error $_.Exception.Message | |
return $null | |
} | |
} | |
## Initialize the PST store | |
$namespace = $Outlook.GetNameSpace("MAPI") | |
## Attach the PST to the Outlook session | |
$namespace.AddStore($PstFilePath) | |
$pstOutlookStore = $namespace.Session.Folders.GetLast() | |
Write-Verbose "PST [$PstFilePath] attached as [$($pstOutlookStore.Name)]." | |
## Start export. | |
Write-Verbose "Start public folder export to [$PstFilePath]." | |
[void]$PublicFolderToExport.CopyTo($pstOutlookStore) | |
Write-Verbose "Start public folder export is finished." | |
## Detach PST from Outlook | |
$namespace.RemoveStore($pstOutlookStore) | |
Write-Verbose "PST [$PstFilePath] detached." | |
$outlook.Application.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment