简体   繁体   中英

Add user to group based on their attribute department with Powershell in AD

Hello guys I would like to ask for little help I was struggling with this for a while so Il be really glad if someone could help me with this:)

The idea is: We have users with the filled department attribute (ex. LCZ_10960-udrzba rezie , LCZ_40900-financni utvar , etc...) and we have created security groups that look like CZ-udrzba_rezie_10960 , CZ-financni_utvar_40900 , etc... And that what I want from the script is to search through specific OU for users and check their department attribute and if they have forex. LCZ_10960-udrzba rezie in it then add this user to group CZ-udrzba_rezie_10960 or if another user has CZ-financni_utvar_40900 in the department then add this user the group LCZ_40900-financni utvar...

Hope I explain it good:)

I already create the script but that is only for add single group...

Get-ADUser -SearchBase "XY,DC=local" -Filter 'Department -like "LCZ_10960-udrzba rezie"' | Foreach{Add-ADGroupMember -Identity "CZ-udrzba_rezie_10960" -Members $_}

Thanks for the help guys!

In this case, I would create a lookup Hashtable linking the department names and the group names together:

# lookup hashtable:
# Keys are the Department names from the user attributes, the Values contain the Group names
$deptGroups = @{
    'LCZ_10960-udrzba rezie'   = 'CZ-udrzba_rezie_10960'
    'LCZ_40900-financni utvar' = 'CZ-financni_utvar_40900'
    # more Department-to-Group mappings go here
}

Then you can use code like this:

foreach ($dept in $deptGroups.Keys) {
    $users = Get-ADUser -SearchBase "XY,DC=local" -Filter "Department -eq '$dept'" -ErrorAction SilentlyContinue
    if ($users) {
        # $deptGroups[$dept] has the group name from the lookup table
        # you can supply an array of members with Add-ADGroupMember, so no need for a ForEach-Object loop
        Add-ADGroupMember -Identity $deptGroups[$dept] -Members $users
    }
    else {
        Write-Warning "No users found for department '$dept'.."
    }
}

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