I'm trying to write a script that removes users from a security group if they aren't in a specific OU.
I'm having trouble comparing my array of users from the OU, to the array of users from the security group.
To test I looped through the content in $testGroup
and $userList
. Both look similar to me but it's clear they don't compare as just outputting $userList -contains $user
gives me a bunch of false
results even though it should be true.
$userList = @()
$testGroup = @()
#Get current members of group. Using this instead of get-adgroupmember due to speed
$testGroup = Get-AdGroup "testGroup" -properties member | select-object -ExpandProperty member | get-aduser
#Define OUs that we want to get members from
$OUlist = "OU1","OU2"
#Populate $userList with members of each OU
$OUlist | foreach {
$userList += get-aduser -filter {Enabled -eq $True} -SearchBase "OU=$_,DC=dc,DC=dc2,DC=dc3"
}
#Check the group for anyone no longer in one of the approved OUs
$testGroup | foreach {
if($userList -notcontains $user){
#remove the user from $testGroup
}
}