Active Directory is a powerful tool for managing users and groups in a Windows environment. One of the most often-repeated tasks for administrators is to add or remove users from Active Directory groups. In this article, we will explore how to perform this task using PowerShell.
To add a user to an Active Directory group, you can use the following PowerShell cmd:
Where “GroupName” = the name of the group in which you want the users to be added.
Multiple users can be specified in the above command, by separating each of the user names with commas.
For example, to add the users "SalesGuy1" and "SalesDude2" to the group "Sales", use the following command:
If you need to add a large number of users to a group, you can import a CSV file containing the users. For example, you can create a file named "SalesUsers.csv" that contains a list of users in the following format:
Username
SalesGuy1
SalesDude2
Then, you can use the following command to add the users in the CSV file to the "Sales" group:
This command uses the Import-Csv cmdlet to read the CSV file and then channels the results to the ForEach-Object cmdlet. The ForEach-Object cmdlet then calls the Add-ADGroupMember cmdlet for each user in the file.
To remove a user from an Active Directory group, you can use the following PowerShell command:
Where “GroupName” = the name of the group in which you want the users to be added.
Like above, multiple users can be specified in the above command, by separating each of the user names with commas.
For example, to remove the users "SalesGuy1" and "SalesDude2" from the group "Sales", use the following command:
Similar to adding users, you can also use a CSV file to specify the users to remove from a group. For example, you can create a file named "SalesUsers.csv" that contains a list of users in the following format:
Username
SalesGuy1
SalesDude2
Then, you can use the following command to remove the users in the CSV file from the "Sales" group:
This command uses the same approach as the one used for adding users. It reads the CSV file and pipes the results to the ForEach-Object cmdlet, which calls the Remove-ADGroupMember cmdlet for each user in the file.