Nested foreach question

Welcome Forums General PowerShell Q&A Nested foreach question

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 7 years ago.

  • Author
  • #5764

    Points: 0
    Rank: Member

    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 {$ -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={$_.DisplayName}},
    @{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]((($_.TotalItemSize.Split('('))[1]).Split())[0].Replace(',','')
    $Size += $Bytes
    $dbStats.Add($_.Name,@{'Mailbox'=$dbCount;'Items'=$Items;'Size'=("{0:N1}" -f ($Size / 1GB))})

The topic ‘Nested foreach question’ is closed to new replies.