Need PowerShell script to update “Department” properties for all users belonging to a specific AD group

We have Windows 2012 R2 Active Directory Domain. “Department” field for some of the users in our domain needs to be updated with the appropriate department info.

Updating “Department” properties for all users in AD one by one will take long time. I need PowerShell script to do it automatically. I need PowerShell script based on Microsoft AD cmdlets not Quest cmdlets.

As an example, PowerShell should get the list of all users belonging to the “HR” AD group and add/update “Department” field of each AD account with the entry of “Human Resources Staff member”

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Create a list of departments in Excel and save it as Departments.csv
It should have two columns with header names ADGroup and departmentRun PowerShell or the PowerShell ISE as Administrator.
Change directory to the location where the .CSV file is saved.
To use your department list, import it to a variable $Departments:

Then making changes I always use the -WhatIf switch for testing. It will give the list of objects the changes will be applied to, without actually making any changes. If the list looks good, run the same one-lines without the -WhatIf switch.

To see the result, get the same list of the affected users int the $usr variable:

We already piping Get-ADGroupMember to SetADUser.
If you are doing this for only a subset of all ADGroups, you will have to list the name of your groups, which is half of the .CSV
If the mapping between groups and departments are arbitrary, you have to list the department name for each group (second half of CSV).
Only way to avoid typing group names, is if you are going through all the groups, or a can come up with a wildcard / filter for the groups. For example "abc*", meaning group names starting with abc.
Only way to avoid typing Department names, is if they can be somehow deducted from the group name, for example, by adding "Staff member" to "HR", resulting in "HR Staff member"
We may be able to generate the csv file from your existing users programmatically (is some of them already have the proper department name), but I don't know how consistent is your environment.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.