Hello, today I will share in detail the script I prepared for a need.
The script checks the mailboxes of the users in the OU you provided and distributes the mailboxes in a CSV format of 250GB. The CSV report includes the mail address and the DB it will be in. The DB names are named as DB01, DB02, DB03 for example, and when you perform the distribution process, you can set the DB size to be 250GB.
If we want to examine the main lines of the script, we can break it down as follows.
It asks the user to enter the OU (Organizational Unit) Distinguished Name (DN). This DN is PowerShell given by Get-Mailbox
is used in the command.
$ouDN = Read-Host "Please enter the distinguished name (DN) of the OU"
All mailboxes in the OU are listed. This Get-Mailbox
is performed with the command. -OrganizationalUnit
parameter returns mailboxes under a specific OU. -ResultSize Unlimited
parameter ensures that all mailboxes are fetched.
$mailboxes = Get-Mailbox -OrganizationalUnit $ouDN -ResultSize Unlimited | Get-MailboxStatistics | Select DisplayName, TotalItemSize, Database
- The script then starts a loop where the size of each mailbox is calculated and added to the existing database until it reaches the 250GB limit.
- Once the 250GB limit is exceeded, a new database is created and the next mailbox is added to the new database. This process is repeated until all mailboxes are assigned to fit within the limit.
- This data is written to a CSV file that contains the name of each mailbox, the database to which it is assigned, and the size of the mailbox.
$newDbs | Export-Csv -Path "new_dbs.csv" -NoTypeInformation -Encoding UTF8
<#
=============================================================================================
Name = Cengiz YILMAZ
Date = 1.03.2023
www.cengizyilmaz.net
www.cozumpark.com/author/cengizyilmaz
============================================================================================
#>
# Prompt for DN of the OU
$ouDN = Read-Host "Please enter the distinguished name (DN) of the OU"
# Get all mailboxes in the OU
$mailboxes = Get-Mailbox -OrganizationalUnit $ouDN -ResultSize Unlimited | Get-MailboxStatistics | Select DisplayName, TotalItemSize, Database
$newDbs = @()
$dbSize = 0
$dbCount = 1
foreach ($mailbox in $mailboxes) {
$mailboxSize = $mailbox.TotalItemSize.Value.ToGB()
if (($dbSize + $mailboxSize) -le 250) {
# add to current DB
$newDbs += New-Object PSObject -Property @{
'Mailbox' = $mailbox.DisplayName
'DB' = "DB$dbCount"
'SizeInGB' = $mailboxSize
}
$dbSize += $mailboxSize
} else {
# create a new DB
$dbCount++
$dbSize = $mailboxSize
$newDbs += New-Object PSObject -Property @{
'Mailbox' = $mailbox.DisplayName
'DB' = "DB$dbCount"
'SizeInGB' = $mailboxSize
}
}
}
# Export to CSV format with UTF8 encoding
$newDbs | Export-Csv -Path "new_dbs.csv" -NoTypeInformation -Encoding UTF8