0
votes

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
1
You are doing $user = and then iterating through $users. Change $user = to $users = . You're also doing the same mistake with $Group =.Mark Wragg

1 Answers

1
votes

Don't define the AD groups as separate columns in the CSV. Make the groups one column with a comma (or other delimiter) separated string:

SamAccountName,Groups
user1,"Group1,Group2,Group3,Group4"
user2,"Group2,Group3"
user3,"Group5"

That way you can handle the groups from the CSV like this:

$csv = Import-Csv .\GroupsToRemove.csv

foreach ($user in $csv) {
    $groups = $user.Groups -split ',' |
              Get-ADGroup |
              Select-Object -Expand DistinguishedName
    Remove-ADPrincipalGroupMembership $user.SamAccountName -Member $groups -Confirm:$false
}