I am trying to create a CSV for AD cleanup work that will contain a couple hundred users' SamAccountName
and a list of groups to remove the user from. Each user will have a different list of groups to remove them from.
CSV will look like this:
SamAccountName,ADgroupName1,ADgroupName2,ADgroupName3,ADgroupName4,etc... user1,Group1,Group2,Group3,Group4 user2,Group2,Group3,,, user3,Group5,,,,
The script I have so far:
# Get the list of SAMAccountNames
$user = Import-Csv .\GroupsToRemove.csv | Select-Object -ExpandProperty SAMAccountName
foreach ($user in $users) {
# Loop through the user list and select the list of groups to remove for each user
# from the CSV and set to the $Groups array
$Group = @()
$Group = %{(Import-Csv .\GroupsToRemove.csv | Where-Object {$_.SamAccountName -eq $user})} | select "GroupName*"
foreach ($group in $Groups) {
# Remove the AD groups from each User
Remove-ADPrincipalGroupMembership $user -Member $Group -Confirm:$false
}
}
I think part of the problem is that when I'm importing the group names from the CSV it also adds the column names into the $Group
array? So the Remove-ADPrincipalGroupMembership
command is failing?
$groups
output is like below:
GroupName1 : Group1 GroupName2 : Group2 GroupName3 : Group3 GroupName4 : Group4
$user =
and then iterating through$users
. Change$user =
to$users =
. You're also doing the same mistake with$Group =
. – Mark Wragg