Search code examples
powershellexchange-server-2010

Left padding a string to sort accordingly


I have to get the database with the max space free in a exchange 2010 however as this gonna be launched from a pipeline in c#, I'm trying to sort the results and then pick the first row.

If I try using the field AvailableNewMailboxSpace, it is sorted using the string values instead the double values:

 Get-MailboxDatabase  -Status | Select Name,AvailableNewMailboxSpace | Sort-Object DatabaseSize

Name           AvailableNewMailboxSpace    
----           ------------------------    
DBMB03         123.1 MB (129,073,152 bytes)
DBMB04         114.1 MB (119,635,968 bytes)
DBMB02         115.6 MB (121,176,064 bytes)
DBMB10         224.4 MB (235,307,008 bytes)
DBMB01         81.47 MB (85,426,176 bytes) 

I guess I must left pad zeros in the string to get the right order but I don't know how.

I have to achieve it in a single line because this gonna be launched using a pipeline command in c#.

This is my attempt:

Get-MailboxDatabase  -Status |`
Sort (("0" * (10 - {$_.AvailableNewMailboxSpace.Substring(0, $_.AvailableNewMailboxSpace.IndexOf("MB") - 1)}.length)) + `
{$_.AvailableNewMailboxSpace.Substring(0, $_.AvailableNewMailboxSpace.IndexOf("MB") - 1)}) | Select Name,AvailableNewMailboxSpace

Solution

  • The best way would be to use the native methods: ToKB(),ToMB(),ToGB() etc:

     Get-MailboxDatabase -Status | Select Name,@{n='AvailableNewMailboxSpaceMB';e={$_.AvailableNewMailboxSpace.Value.ToMB()} | Sort-Object DatabaseSize
    

    or

     Get-MailboxDatabase -Status | Select Name,AvailableNewMailboxSpace | Sort-Object {$_.AvailableNewMailboxSpace.Value.ToMB()}
    

    If for some reason you can't do that then do string manipulation:

     Get-MailboxDatabase -Status | Select Name,AvailableNewMailboxSpace | Sort-Object {[double]$_.AvailableNewMailboxSpace.Split()[0]}