So im working on this script that will check if the user in target_group exist in source_group, if not it will be removed. But i cant get i to work 100%, any ideas is greatly appreciated.
When you crosspost the same question at the same time to different forums you should at least post links to the other forums along with your question to avoid people willing to you help making their work twice or more.
[quote quote=215805]When you crosspost the same question at the same time to different forums you should at least post links to the other forums along with your question to avoid people willing to you help making their work twice or more.
I love compare-object but I’ve learned not to depend on it for this type of thing. I think what you’re needing is to compare a name to an array of names. I’ve put the source/group names into variables for ease of future expansion. See the following
#Source and target groups
$source_group_name = "Source"
$target_group_name = "Target"
$source_group = Get-ADGroup -filter {samaccountname -like $source_group_name}
$target_group = Get-ADGroup -filter {samaccountname -like $target_group_name}
#Get members
$source_members = Get-ADGroupMember -Identity $source_group.distinguishedname
$target_members = Get-ADGroupMember -Identity $target_group.distinguishedname
#initialize slow array *** Performance/time concern on large datasets ***
$removedusers = @()
#If in the target but not the source => remove them
foreach($member in $target_members){
if($member.samaccountname -notin $source_members.samaccountname){
"{0} does not exist in {1} and will be removed" -f $member.samaccountname,$target_group.name
Remove-ADGroupMember -Identity $target_group.DistinguishedName -Members $member.samaccountname -WhatIf
$removedusers += $(new-object -TypeName PSObject -property @{
SamAccountName = $member.samaccountname
DistinguishedName = $member.DistinguishedName
GroupRemovedFrom = $target_group.DistinguishedName
})
}
}
if ($removedusers){write-output $removedusers}