Nested foreach question

by penguinviw at 2013-04-04 12:25:16

My script collects the sub OUs under the KT OU, gets the mailbox info for each mailbox in each OU and outputs the mailbox info grouped by OU. What I can not seem to get it to do is put a line at the end of each group of OUs with the total space used by the mailboxes in that OU. It provides the total space used, but outputs as many lines as there is mailboxes in that OU. The math is right, it just produces duplicate lines of the totals. Here is my code:
Import-Module ActiveDirectory
if(!(Get-PSSnapin |
Where-Object {$.name -eq "Microsoft.Exchange.Management.PowerShell.E2010"})) {
ADD-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
# Variables
$ErrorActionPreference = "SilentlyContinue"
$WarningPreference = "SilentlyContinue"
$oulist = Get-OrganizationalUnit "KT" -SingleNodeOnly
# End Variables
ForEach ($Ounames in $Oulist) {
Write-Host "------"n $Ounames.Name n"------"
ForEach ($Mailbox in (Get-Mailbox -ResultSize Unlimited -OrganizationalUnit $Ounames.Name)){
Get-mailboxstatistics $Mailbox | Select @{label="User";expression={$
@{label="Storage Limit";expression={$.StorageLimitStatus}},
ServerName, Database
$CalculateOuSize = (Get-Mailbox -OrganizationalUnit $Ounames.Name | Get-mailboxstatistics | Measure-Object -Property 'TotalItemSize'-Sum).Sum
[int]$TotalOuSize = $CalculateOuSize/1048576
Get-Mailbox -OrganizationalUnit $Ounames.Name | Get-mailboxstatistics | Select @{label="Total OU MailBox Size";expression={$TotalOuSize}}
Write-Host "-------------------------------------------------"
Write-Host n n

by ArtB0514 at 2013-04-04 12:30:43
I do something similar, but from the mailbox server perspective rather than the user perspective. Maybe this can help you. $Servers is the list of Exchange servers.

$dbStats = @{}
Foreach ($mbxServer in ($Servers | Where {$
.ServerRole -eq "Mailbox"})) {
$mbxStats = Get-MailboxStatistics -Server $mbxServer.Name
$DBs = $mbxStats | Group Database
$DBs | foreach {
$dbCount = $.Count
$Items = $Size = 0
.Group | Foreach {
$Items += $.ItemCount
$Bytes = [int64]((($
$Size += $Bytes
$dbStats.Add($_.Name,@{'Mailbox'=$dbCount;'Items'=$Items;'Size'=("{0:N1}" -f ($Size / 1GB))})