powershellactive-directoryexchange-management-shell

Extract users from AD group and add them to Mailbox


I want to make a powershell script to extract an AD group and add the members to a specific mailbox. In that group is a group that i dont want to extract (doNotExtract). That is what i have so far:

Import-Module ActiveDirectory
$csv = @"
Mailbox,GroupName
Mailbox1,Group1
"@ | ConvertFrom-Csv

$ExcludedUsers = Get-ADGroupMember -Identity "doNotExtract" -Recursive | Select-Object -ExpandProperty SamAccountName

$csv | ForEach-Object {
    $mailbox = $_.Mailbox

    Get-ADGroupMember -Identity $_.GroupName -Recursive |

    Where-Object { ($ExcludedUsers -notcontains $_.SamAccountName) -and ($_.objectclass -eq 'user') } |
    ForEach-Object {
        Add-MailboxPermission -Identity $mailbox -User $_.SamAccountName -AccessRights FullAccess -InheritanceType All
    }
}

In the AD group are the following objects:

doNotExtract
User1
User2

I then start the script in the exchange management shell. But then it adds only User1 and User2 doesnt gets fullaccess on Mailbox1.

And i cant find the problem in the script...


Solution

  • In this case, the error was that the User2 was also in the donotextract group.