get-mailboxstatistics | sort-object is PSSession


I’m trying to optimize a poller for our environment and ran into a weird thing–I don’t know what to make of it. I tested various code on the exchange server and it was running faster than the original code. Then I tried it again in a PSSession to see if it is still faster remotely, but in the session it broke. Turns out, get-mailboxstatistics | sort-object works differently in a PSSession than the exchange console. I’ll demonstrate with an example.

On the server, I run
C:\Windows\system32>get-mailboxstatistics -server | sort-object -property totalitemsize -descending | select-object -first 1 property totalitemsize


7.782 GB (8,355,492,557 bytes)

Then on my workstation I create a PSSession and run the same command

$cred = get-credential
$session = new-possession -connectionuri -configurationname -credential $cred -authentication negotiate -allowredirection
import-possession $session
get-mailboxstatistics -server | sort-object -property totalitemsize -descending | select-object -first 1 -property totalitemsize


993.9 MB (1,042,175,940 bytes)

By playing with permutation, I found that sort-object in the PSSession sorts from the left, so 7.782 GB is smaller than 993.9 MB. Sort-object running directly on the server sorts the value of byes, the number in the parenthesis. But why? Is this a bug, a problem in our environment, known behavior, or a feature?

I don’t have a huge amount of experience with Exchange and PowerShell, but I noticed something similar with SMTP addresses. Depending on how you ran it, they either came back as strings or as some sort of MailAddress object.

It looks like you’re probably having the same problem; the fact that a number starting with “99” is being sorted to the top of your list probably means that you’re dealing with data in string form. You can code around that, but it’s annoying.

First things first, see what’s really in that TotalItemSize property. Is it a string that contains ‘993.9 MB ( 1,042,175,940 bytes)’ , or is that just something that PowerShell did when formatting the output? Try saving the result of your pipeline to a variable, and run things like:

$largest = get-mailboxstatistics -server | sort-object -property totalitemsize -descending | select-object -first 1 -property totalitemsize


If it really is a string, once you know what’s in that variable, it’s fairly trivial to make the sort work with a cast operator, and possibly a bit of string manipulation.

Yes Dave, spot on. This is Unlimited`1 in the console, but a String remotely.

Thank you!