Hello,
You can use the below updated script.
$groupNamesToSkip = @("MyGroup1", "MyGroup2", "Department*") # TODO: modify me
function SkipGroup($patterns, $name)
{
foreach ($pattern in $patterns)
{
if ($name -like $pattern)
{
return $True
}
}
return $False
}
# Get all groups user is a direct member of
$groupGuids = $Context.TargetObject.GetEx("adm-DirectMemberOfGuid")
# Get the Primary Group ID
$primaryGroupId = $NULL
if ($Context.TargetObject.DirectoryType -eq 1)
{
$primaryGroupId = $Context.TargetObject.Get("primaryGroupID")
}
foreach ($groupGuidBytes in $groupGuids)
{
# Bind to the group
$groupGuid = New-Object "System.Guid" (,$groupGuidBytes)
$groupGuid = $groupGuid.ToString("B")
$groupPath = "Adaxes://<GUID=$groupGuid>"
$group = $Context.BindToObject($groupPath)
if ($group.DirectoryType -eq 1)
{
# Skip Primary Group
if ($group.Get("primaryGroupToken") -eq $primaryGroupId)
{
continue
}
$groupName = $group.Get("sAMAccountName")
}
else
{
$groupName = $group.Get("name")
}
# Skip special groups
if (($groupNamesToSkip -ne $NULL) -and
(SkipGroup $groupNamesToSkip $groupName))
{
continue
}
# Remove user from the group
$group.Remove($Context.TargetObject.AdsPath)
$Context.LogMessage("User %fullname% removed from group $groupName", "Information")
}