Tuesday, 3 March 2009

Combining two commands get-mailbox and get-mailboxstatistics

Did you ever needed to supply a list of mailboxes containing the e-mail address, DisplayName, Database, TotalSize of mailbox and total Items of the mailbox.
There are various ways of obtaining this information but the easiest way would be with powershell.
The information you need is supplied by two commands:
  1. Get-mailbox
  2. Get-mailboxstatistics
So how do you get the information of those two commands in a single output?

Get-mailbox Name select-Object DisplayName,PrimarySmtpAddress,Database
Get-Mailboxstatistics Name Select-Object TotalItemSize,ItemCount

I used to create arrays and then merge them together but for this relatively simple task you need at least 15 lines of code.
So I looked for other ways doing this.

To get the size of a mailbox you use the command:

Get-MailboxStatistics MBXName select TotalItemSize,ItemCount

This will produce:
TotalItemSize is displayed in Bytes which is not easy to work with so you can use the following expression to get it in another format.

Get-MailboxStatistics MBXName select {$_.TotalItemSize.value.toMB()},ItemCount

This will produce:

This is still not easy to work with. We need a different header for the mailbox size.

Get-MailboxStatistics MBXName select @{n="Size(MB)" ;E = {$_.TotalItemSize.value.toMB()}},ItemCount

This will produce:
So we can use an expression to reformat the output. So can we use another command in the same way we reformatted the output? Yes you can.

Get-Mailbox MBXName Select-Object name,primarysmtpaddress,DisplayName,Database, @{e = {Get-MailboxStatistics $_.name select totalItemsize}}

This will produce:
The columnheader of "Get-MailboxStatistics ......" is actually:

Get-MailboxStatistics $_.name PipelineBreakpointerE4078E3092DF4dd9A469F3DC0CBB505C(00000000000000000110) select totalItemsize

This is stil not easy to work with.
If you combine the statement to convert-to-MB with the get-mailboxstatistics you can get something like this:

Get-Mailbox MBXName Select-Object name,primarysmtpaddress, DisplayName,Database,@{n="Size(MB)";e = {$MBXstat = Get-MailboxStatistics $_.name; $MBXstat.totalItemsize.value.toMB()}},@{n="Items"; e = {$MBXstat = Get-MailboxStatistics $_.name ; $MBXstat.itemcount}}

This will output:
If you want to create an overview of a complete database you would use the following command:

Get-Mailbox –Database SRV1\SG01\DB01 Select-Object name,primarysmtpaddress,DisplayName,Database,@{n="Size(MB)";e = {$MBXstat = Get-MailboxStatistics $_.name; $MBXstat.totalItemsize.value.toMB()}},@{n="Items"; e = {$MBXstat = Get-MailboxStatistics $_.name ; $MBXstat.itemcount}}