Last week I needed a quick way to remove a large number of users from an on-premises AD group.
The only info I had was the email address. Now the PowerShell command that I used didn't like to parse the email address so I had to find another way of doin the same thing.
I came up with this, and it's only here because I use this a lot and I don't want to reinvent every script that I make because I can't remember where I put it.
Add Users To Group From CSV:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | # Path to your CSV file $csvPath = "C:\Temp\Add-UserstoGroupFromCSV\Add-UserstoGroupFromCSV.csv" # Import the CSV file $users = Import-Csv -Path $csvPath # Define the group to which you want to add the users $groupName = "Your super secret group name" # $groupName2 = "Your super secret group name2" |
Remove Users From Group From CSV:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | # Path to your CSV file $csvPath = "C:\Temp\Remove-UsersFromGroupFromCSV\Remove-UsersFromGroupFromCSV.csv" # Import the CSV file $users = Import-Csv -Path $csvPath # Define the group from which you want to remove the users $groupName = "Your super secret group name" # $groupName2 = "Your super secret group name2" # Loop through each user in the CSV file foreach ($user in $users) { # Get the email address from the CSV $emailAddress = $user.Email # Find the user in Active Directory by email address $ADUser = Get-ADUser -Filter { EmailAddress -eq $emailAddress } # Check if the user exists if ($adUser) { # Remove the user from the group Remove-ADGroupMember $groupName -Members $ADUser -Confirm:$false #-whatif # Remove-ADGroupMember $groupName2 -Members $aduser -Confirm:$false #-whatif Write-Output "$User has been removed from the $groupname / $groupname2." } else { # Output a message if the user is not found Write-Output "No user found with email address $emailAddress." } } |
No comments:
Post a Comment