0
votes

I need a script to verify if multiple users are a member of a list of AD groups and, if they are, remove them. I've got something like this:

Import-Module ActiveDirectory

$users = Get-Content -Path "C:\users.txt"
$groups = Get-Content -Path "C:\groups.txt"

foreach ($group in $groups) {
    foreach ($user in $users) {
        $members = Get-ADGroupMember -Identity $group -Recursive |
                   Select -ExpandProperty SamAccountName

        if ($members -contains $user) {
            Remove-ADGroupMember -Identity $group.Name -Members $user.SamAccountName -Confirm:$false
            Write-Host "$user has been removed from $group"
        } else {
            Write-Host "$user is not a member of $group"
        }
    }
}

But I get the following error:

Remove-ADGroupMember : Cannot validate argument on parameter 'Identity'. The
argument is null. Provide a valid value for the argument, and then try running
the command again.
At line:12 char:44
+             Remove-ADGroupMember -Identity $group.Name -Members $user.SamAccount ...
+                                            ~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Remove-ADGroupMember], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember
1
the error message states Cannot validate argument on parameter 'Identity'. The argument is null. verify that $group.name (maybe try with $group instead?Guenther Schmitz
If you want to remove them anyway you could use Remove-ADPrincipalGroupMembership. You don't have to check it before. ;-) When you add -ErrorAction SilentlyContinue you wouldn't get errors if one account is not member of a group.Olaf

1 Answers

1
votes

Guessing you are adapting some pre-existing code, as you've got properties in this line that aren't defined in your code:

Remove-ADGroupMember -Identity $group.Name -Members $user.SamAccountName -Confirm:$false

Simple to fix, you just need to change $group.Name to $group and also $user.SamAccountName to $user

Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false