...better than mine!
Can I be cheeky and ask for one more bit?
I have extended so that I have two scripts - one that adds and another that removes. I have also tweaked the output so that each membership change is shown on a line.
It works well in both scenarios, but if the member is already a member (or not) we get a lot of 'warnings'. How would we best put an additional step in so that it checks to see if the user is\isn't a member already before trying the add\remove task?
I have my code below, and where I think we can put a 'check if user is in group' step. I think using the 'Get-AdmGroupMember' CmdLet at this point should work and was wondering if there is a clever way of doing it to return a simple TRUE\FALSE to trigger or escape the subsequent modification?
Import-Module Adaxes
$groupNameTemplate = "Test Group *" # TODO: modify me
# Search groups
$domainName = $Context.GetObjectDomain("%distinguishedName%")
$groups = Get-AdmGroup -Filter {name -like $groupNameTemplate} -Server $domainName -AdaxesService localhost
$groupNames = ""
foreach ($group in $groups)
{
$groupName = $group.Name
# Check if the user is a member of the group
# Is this the best place to perform the initial check?
# Remove the user from the group
try
{
Remove-AdmGroupMember -Identity $group -Members @("%distinguishedName%") `
-Server $domainName -AdaxesService localhost -Confirm:$False -ErrorAction:Stop
$Context.LogMessage("User removed from: $group.Name", "Information")
}
catch
{
$Context.LogMessage("Failed to remove the user from group '$groupName'. Cause: " + $_.Exception.Message, "Warning") # TODO: modify me
continue
}
$groupNames += "$groupName;"
}
if ($groupNames.Length -ne 0)
{
$Context.LogMessage("Group membership processed", "Information") # TODO: modify me
}
else
{
$Context.LogMessage("Failed to remove the user from any of the groups matching the '$groupNameTemplate' template.", "Information") # TODO: modify me
}