简体   繁体   中英

Add users to a certain AD group depending on their Department

I want to automatically add users from a specific Department to a specific AD Security Group.

For example, add all users with the AD Department attribute Sales , Reception or Finance to the Security Group called APP Group .

I've managed to come up with the code beneath which only displays the users regarding the specific Departments.

Can someone explain me how to expand this code so the Users are added to the security group?

Get-ADUser -Filter * -Properties department | 
    Where-Object {$_.department -Like "Sales" -or $_.department -Like "Reception" -or $_.department -Like "Finance"} | 
        Select sAMAccountName, department

You can create an array of the desired users and use this as input for Add-ADGroupMember like this:

$UserList = Get-ADUser -Filter * -Properties department | 
    Where-Object {$_.department -Like "Sales" -or $_.department -Like "Reception" -or $_.department -Like "Finance"} | 
        Select sAMAccountName
Add-ADGroupMember -Identity 'APP Group' -Members $UserList

Using your actual Filter requirements in Get-ADUser -Filter is much faster than piping everything to Where-Object and having it sort through all the users in your domain .

You can then use the pipeline to add the users to the group with Add-ADPrincipalGroupMembership .

$filter = 'Department -eq "Sales" -Or Department -eq "Reception" -Or Department -eq "Finance"'
Get-ADUser -Filter $filter | Add-ADPrincipalGroupMembership -MemberOf 'APP Group'

I've put the filter in variable for readability, but it could be a one-liner:

Get-ADUser -Filter 'Department -eq "Sales" -Or Department -eq "Reception" -Or Department -eq "Finance"' | Add-ADPrincipalGroupMembership -MemberOf 'APP Group'

EDIT:

I can't test as working remotely, but you should just be able to filter out the users in the group already using memberof :

$ADGroup = 'APP Group'
Get-ADUser -Filter 'Department -eq "Sales" -Or Department -eq "Reception" -Or Department -eq "Finance"' | 
    Where-Object {!($_.memberof -like $ADGroup)} |
    Add-ADPrincipalGroupMembership -MemberOf $ADGroup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM