Cleaning out the Skeletons in your mailbox by deleting all the Empty folders with EWS and Get-MailboxFolderStatistics
One of the things you may find if your using Archive or Retention policies a lot is that you end up with skeleton folders in your mailbox. Which are basically the old folders trees that are all now empty because the items have been moved to the Archive or aged out of the Mailbox. To see your skeletons you can use the Get-MailboxFolderStatistics cmdlet and something like this to identify user created folders that are empty.
get-mailboxfolderstatistics $MailboxName | Where-Object{$_.FolderType -eq "User Created" -band $_.ItemsInFolderAndSubFolders -eq 0}
If you want to delete those folders there is no cmdlet to do this so you need to use EWS. Following on from my last post we can take the FolderId from Get-MailboxFolderStatistics convert this Id to a EWSId so we can then bind to the folder in EWS and then delete it using the Delete method.
I've put together a sample script to show how to do this by first using the Get-MailboxFolderStatistics and then in EWS ConvertId and Delete (a soft folder deletion).
The script itself isn't really intelligent in that it doesn't delete a Sub-folder before the Root folder if both are empty (it just depends they way they comes out). It just relies on the Try-Catch to ignore any errors and uses the EWS Folder TotalCount property as a secondary check.
As this script deletes things (some of which maybe be hard to recover if you don't want them deleted) you should do your own testing and use at your own risk.
I've put a download copy of this script here the code itself looks like
get-mailboxfolderstatistics $MailboxName | Where-Object{$_.FolderType -eq "User Created" -band $_.ItemsInFolderAndSubFolders -eq 0}
If you want to delete those folders there is no cmdlet to do this so you need to use EWS. Following on from my last post we can take the FolderId from Get-MailboxFolderStatistics convert this Id to a EWSId so we can then bind to the folder in EWS and then delete it using the Delete method.
I've put together a sample script to show how to do this by first using the Get-MailboxFolderStatistics and then in EWS ConvertId and Delete (a soft folder deletion).
The script itself isn't really intelligent in that it doesn't delete a Sub-folder before the Root folder if both are empty (it just depends they way they comes out). It just relies on the Try-Catch to ignore any errors and uses the EWS Folder TotalCount property as a secondary check.
As this script deletes things (some of which maybe be hard to recover if you don't want them deleted) you should do your own testing and use at your own risk.
I've put a download copy of this script here the code itself looks like
- ## Get the Mailbox to Access from the 1st commandline argument
- $MailboxName = $args[0]
- ## Load Managed API dll
- Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
- ## Set Exchange Version
- $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2
- ## Create Exchange Service Object
- $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)
- ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials
- #Credentials Option 1 using UPN for the windows Account
- $psCred = Get-Credential
- $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())
- $service.Credentials = $creds
- #Credentials Option 2
- #service.UseDefaultCredentials = $true
- ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates
- ## Code From http://poshcode.org/624
- ## Create a compilation environment
- $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
- $Compiler=$Provider.CreateCompiler()
- $Params=New-Object System.CodeDom.Compiler.CompilerParameters
- $Params.GenerateExecutable=$False
- $Params.GenerateInMemory=$True
- $Params.IncludeDebugInformation=$False
- $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null
- $TASource=@'
- namespace Local.ToolkitExtensions.Net.CertificatePolicy{
- public class TrustAll : System.Net.ICertificatePolicy {
- public TrustAll() {
- }
- public bool CheckValidationResult(System.Net.ServicePoint sp,
- System.Security.Cryptography.X509Certificates.X509Certificate cert,
- System.Net.WebRequest req, int problem) {
- return true;
- }
- }
- }
- '@
- $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
- $TAAssembly=$TAResults.CompiledAssembly
- ## We now create an instance of the TrustAll and attach it to the ServicePointManager
- $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
- [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
- ## end code from http://poshcode.org/624
- ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use
- #CAS URL Option 1 Autodiscover
- $service.AutodiscoverUrl($MailboxName,{$true})
- "Using CAS Server : " + $Service.url
- #CAS URL Option 2 Hardcoded
- #$uri=[system.URI] "https://casservername/ews/exchange.asmx"
- #$service.Url = $uri
- ## Optional section for Exchange Impersonation
- #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)
- function ConvertId{
- param (
- $OwaId = "$( throw 'OWAId is a mandatory Parameter' )"
- )
- process{
- $aiItem = New-Object Microsoft.Exchange.WebServices.Data.AlternateId
- $aiItem.Mailbox = $MailboxName
- $aiItem.UniqueId = $OwaId
- $aiItem.Format = [Microsoft.Exchange.WebServices.Data.IdFormat]::OwaId
- $convertedId = $service.ConvertId($aiItem, [Microsoft.Exchange.WebServices.Data.IdFormat]::EwsId)
- return $convertedId.UniqueId
- }
- }
- ## Get Empty Folders from EMS
- get-mailboxfolderstatistics $MailboxName | Where-Object{$_.FolderType -eq "User Created" -band $_.ItemsInFolderAndSubFolders -eq 0} | ForEach-Object{
- # Bind to the Inbox Folder
- "Deleting Folder " + $_.FolderPath
- try{
- $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId((Convertid $_.FolderId))
- $ewsFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
- if($ewsFolder.TotalCount -eq 0){
- $ewsFolder.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete)
- "Folder Deleted"
- }
- }
- catch{
- }
- }