PowerShell: Get Largest Mailbox Folders, One-Line Command

Another quick one-liner I’ve just figured out.  This will get the 20 largest folders in the mailbox sorted into descending order of size.  There was a big gotcha I needed to figure out which I go into after the break.

Get-MailboxFolderStatistics "test@test.co.uk" | 
Select-Object Identity,@{name="Size";expression={
[decimal]($_.FolderAndSubFolderSize.Split(' ')[0])}} |
 ? {$_.Size -gt 0} |
 Sort-Object -Property Size -Descending |
 Select -First 20

This is the command to get the 20 largest folders in the “test@test.co.uk” mailbox.  The command breaks down as follows;

Get-MailboxFolderStatistics "test@test.co.uk" |

This part gets the raw folder statistics for the mailbox we’re interested in and pipes the result onto the next part of the command.  Each folder within the mailbox is a separate object in the pipeline with a number of properties.

Select-Object Identity,@{name="Size";expression={
[decimal]($_.FolderAndSubFolderSize.Split(' ')[0])}} |

Here we see the ‘gotcha’ I mentioned.  The property we want is FolderAndSubFolderSize but unfortunately the Get-MailboxFolderStatistic command formats this property as a string (in the format “104 B (Bytes)”).  This means ordering them doesn’t work (because “2000 B (Bytes)” will come before “10000 B (Bytes)” in descending order of strings, which is incorrect for numbers).

So, we need to convert to a number format before we sort them.  We do that by creating a new object with two properties;  the first is the Identity from the passed object and the second is a new property we calculate from the FolderAndSubFolderSize property.

Looking at the format of FolderAndSubFolderSize we can see that the number portion we’re interested in is always before a [Space] character in the string.  So if we split the string on the [Space] character and take the first element of the result array (i.e. the first portion of the string until the first [Space]) we have the number we want.

We then cast that portion of the string as a [decimal] and use that for a new property called Size. We now have an object with Identity and Size properties which is passed on through the pipeline.

? {$_.Size -gt 0} |

Using the alias for Where-Object (?) we then filter out any objects with a Size equal to 0 and pass the filtered objects on through the pipeline (we don’t need to see empty folders).

Sort-Object -Property Size -Descending |
 Select -First 20

Finally we sort all the objects in descending order of size and then select the first 20 items.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: