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
Cannot validate argument on parameter 'Identity'. The argument is null.
verify that$group.name
(maybe try with$group
instead? – Guenther Schmitz-ErrorAction SilentlyContinue
you wouldn't get errors if one account is not member of a group. – Olaf