Skip to content

Instantly share code, notes, and snippets.

@LVLAaron
Created January 24, 2014 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LVLAaron/8605487 to your computer and use it in GitHub Desktop.
Save LVLAaron/8605487 to your computer and use it in GitHub Desktop.
Find the smallest exchange database (this is where you want to create new mailboxes) Use in various other scripts.
# Script to return the smallest database on a specified server
# Written by Ben Lye - 20th August 2008
# By default the smallest database is determined by summing the size of all the mailboxes in each database.
# Optionally the -edb flag can be specified to make the script look at the EDB file size instead.
# If no server name is specified on the command line one will be prompted for
# Usage:
# Get-SmallestDatabase.ps1 [-Server <Server name>] [-edb]
# Get the command line parameters
Param ([string]$server,[switch]$EDB)
# Load the Exchange 2007 snap-in if they are not already loaded
Add-PSSnapIn -Name Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction SilentlyContinue
# Check that the Exchange 2007 snap-in loaded
$snapin = Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction SilentlyContinue
If (-not $snapin) {
Write-Host "Error: Exchange 2007 snap-in not found" -ForegroundColor "Red"
Write-Host
break
}
# Prompt for a server name if one wasn't passed in
if (-not $server) {
$server = Read-Host "Server name"
}
# Find any databases on the specified server
$databases = Get-MailboxDatabase -Server "$server" -ErrorAction SilentlyContinue
# Error if there are no databases found
If (-not $databases) {
Write-Host "Error: No databases found for server $server" -ForegroundColor "Red"
Write-Host
$break
}
If ($databases) {
# Prepare some variables for storing the name and size of the smallest database
$smallestdbsize = $null
$smallestdb = $null
# Loop through each of the databases
Foreach ($database in $databases) {
If ($EDB) {
# Get the size of the .edb file
$dbsize = (get-childitem ("\\" + $database.Server + "\" + $database.EDBFilePath.PathName -replace(":","$")) | select-object name,length).length
} Else {
# Get the database size in bytes by summing the size of all mailboxes in the database
$dbsize = (Get-MailboxStatistics -Database $database.Identity | Measure-Object -Property TotalItemSize -Sum).Sum
}
# Compare the sizes to find the smallest DB
if (($dbsize -lt $smallestdbsize) -or ($smallestdbsize -eq $null)) {
$smallestdbsize = $dbsize
$smallestdb = $database
}
}
# Return the smallest database
$smallestdb
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment