Function to return smallest db is not working
<p>I have some PoSH function that I found online that will return the smallest exchange database. In testing the script I found that it does not work as intended; that is the smallest database returned is not actually correct.</p>

<p>This is the code:</p>

<pre><code>#http://izzy.org/scripts/Exchange/Admin/Create-Mailbox.ps1
$DBFilter = "MBX_*" # Limit databases to only those that start with "Primary"

Function Get-SmallestDB {
    Try {
        $MBXDbs = Get-MailboxDatabase | ? {$_.Identity -like $DBFilter } 
        $MBXDBCount = $PSSessions.Count
    }
    Catch {
        $MBXDBCount =  0
    }
    If (!$MBXDbs) {ExitScript "find databases with a name that matches a filter of [$DBFilter]." $False}

    # Loop through each of the MBXDbs
    ForEach ($MBXDB in $MBXDbs) {
        # Get current mailboxes sizes by summing the size of all mailboxes and "Deleted Items" in the database
        $TotalItemSize = Get-MailboxStatistics -Database $MBXDB | %{$_.TotalItemSize.Value.ToMB()} | Measure-Object -sum
        $TotalDeletedItemSize = Get-MailboxStatistics -Database $MBXDB.DistinguishedName | %{$_.TotalDeletedItemSize.Value.ToMB()} | Measure-Object -sum
        $TotalDBSize = $TotalItemSize.Sum + $TotalDeletedItemSize.Sum
        Write-Host "$MBXDB $($TotalItemSize.Sum) $($TotalDeletedItemSize.Sum) $TotalDBSize"
        # Compare the sizes to find the smallest DB
        If (($TotalDBSize -lt $SmallestDBsize) -or ($SmallestDBsize -eq $null)) {
            $SmallestDBsize = $DBsize
            $SmallestDB = $MBXDB }}
    return $SmallestDB }
</code></pre>

<p>Basically when i run this in my Exchange environment it returns "MBX_20" as $SmallestDB. But I added some debug code (Write-Host to output values for $($TotalItemSize.Sum, $($TotalDeletedItemSize.Sum) and $TotalDBSize and the results are:</p>

<pre><code>MBX_1 140561 5180 145741
MBX_2 190865 15882 206747
MBX_3 174393 1714 176107
MBX_4 122362 6479 128841
MBX_5 108833 15409 124242
MBX_6 196569 13793 210362
MBX_7 114298 2144 116442
MBX_8 140896 21558 162454
MBX_9 160024 13364 173388
MBX_10 188268 6046 194314
MBX_11 132256 15300 147556
MBX_12 173262 6486 179748
MBX_13 101107 3761 104868
MBX_14 131453 4930 136383
MBX_15 134682 4424 139106
MBX_16 146767 12484 159251
MBX_17 155224 2074 157298
MBX_18 117147 12270 129417
MBX_19 129101 6597 135698
MBX_20 134675 9059 143734
</code></pre>

<p>As you can see MBX_20 with 143734 is NOT the smallest db. I am now trying to fix the code but I am not very good with PoSH. Any tips?</p>