ForEach Trouble - I'm sure I'm Missing Something Small

I know what I’m doing wrong, but I don’t know how to code myself out of the problem.

I am trying to get all of the users for a specific Distribution Group, but I’m only using one variable. Can someone help get me out of this paper bag I’ve put over my head?



$SharedMailboxes = @()
$Rollup = @()
$i = 0

$SharedMailboxes = Get-EXORecipient -ResultSize Unlimited -Filter {(EmailAddresses -like ‘’) -or (EmailAddresses -like '’) -or (EmailAddresses -like ‘’) -or (EmailAddresses -like '’)} | ? RecipientTypeDetails -eq “SharedMailbox”
ForEach ($SharedMailbox in $SharedMailboxes){
$MailboxUsers = Get-EXOMailboxPermission $SharedMailbox.Identity |? user -like ‘@
ForEach ($MailboxUser in $MailboxUsers){
$Name = Get-EXORecipient -Identity $MailboxUser.User
$item = New-Object PSObject
$item | Add-Member -Type NoteProperty -Name ‘Distribution Group’ -Value $SharedMailbox.DisplayName
$item | Add-Member -Type NoteProperty -Name ‘Distribution Group Email’ -Value $SharedMailbox.PrimarySMTPAddress
$item | Add-Member -Type NoteProperty -Name ‘UPN’ -Value $Name.DisplayName
$item | Add-Member -Type NoteProperty -Name ‘Primary Email’ -Value $Name.PrimarySMTPAddress
$Rollup += $item
Write-Progress -activity “Researching Distro” -status “Distro: $i of $($SharedMailboxes.Count)” -percentComplete (($i / $SharedMailboxes.Count) * 100)


Hello R_Martin,
You are closing your nested foreach loop to soon. Simply move closing bracket “}” from line #10 to line #20.

Also I noticed that you are using += operator to dynamically add objects to $Rollup array. += Operator is not best approach as it is very time consuming. And during execution of your script your Office365 session might be dropped and script will fail. I would suggest to use ArrayList.
Substitute line #2 to following

$Rollup=New-Object System.Collections.ArrayList

and line #16 to


Hope that helps.

Hello Andy!

Thank you for your help. It works perfectly now. The only thing I added was on line 16 I did the following to keep it from counting up on screen.

$Rollup.Add($item) > $Null
Thanks again!

Glad that you figured it out.

More PowerShellish way would be to pipe it to Out-Null


Hope that helps.

Where do those red spaces come from again (non-breaking spaces or nbsp?