Check if user is a member and remove

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 answer

  • answered 2019-02-04 09:24 James C.

    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