Get smallest Exchange Database in PowerShell


I needed to adapt some scripts that create a user with mailbox for Exchange 2010. The existing scripts had a hardcoded database for new mailboxes.

I wanted the mailbox to be created in the smallest database, but how do we determine this?

For Exchange 2010 this is fairly easy using PowerShell:

# Add Exchange Snapins
if ((Get-PSSnapin | where {$_.Name -match "Exchange.Management"}) -eq $null) { Add-PSSnapin Microsoft.Exchange.Management.* }

# Get largest possible size
$size = [Microsoft.Exchange.Data.ByteQuantifiedSize]::MaxValue.ToBytes()
foreach ($db in Get-MailboxDatabase -Status)
	Write-Host "Database:" $db.Name "Size:" $db.DatabaseSize.ToBytes()

	# Is the Database smaller than previous smallest size
	if ( $db.DatabaseSize.ToBytes() -lt $size )
		# This database is smaller, store size and db
		$size = $db.DatabaseSize.ToBytes()
		$ExDB = $db

Write-Host "Smallest Database:" $ExDB.Name "Size:" $ExDB.DatabaseSize.ToBytes()