Skip to content

Instantly share code, notes, and snippets.

@junecastillote
Created June 21, 2023 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junecastillote/93cd6d6355fab595b7185f27e3e4e20d to your computer and use it in GitHub Desktop.
Save junecastillote/93cd6d6355fab595b7185f27e3e4e20d to your computer and use it in GitHub Desktop.
Export Public Folder to PST with PowerShell and Outlook COM Object
[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