The script removes a user from all groups (including cloud ones) except for the primary group and groups specified in the $groupNamesToSkip variable. The script can be used in business rules, custom commands and scheduled tasks.
The $groupNamesToSkip variable specifies the groups from which the user should not be removed. If set to $NULL the user for which the script is executed will be removed from all groups except for the primary one.
$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)
# Check if the group is dynamic
try
{
$dynamicMembership = $group.Get("adm-AzureDynamicMembership")
}
catch
{
$dynamicMembership = $False
}
if ($dynamicMembership -eq $True)
{
continue
}
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)
}
This version of the script sends an email for each user with a list of groups the user has been removed from.
Parameters:
- $to - Specifies a comma-separated list of recipients of the e-mail notifications. You can use value references to specify recipients. For example, if you use the %adm-ManagerEmail% template, the email will be sent to user managers.
- $subject - Specifies the subject of the email notifications.
- $reportHeader - Specifies template for the email notification header. In the emplate, the {0} placeholder will be replaced with a link to the user account in Adaxes Web interface.
- $reportFooter - Specifies template for the email notification footer.
- $groupNamesToSkip - Specifies groups from which the user should not be removed. If set to $NULL the user for which the script is executed will be removed from all groups except for the primary one.
You can use value references in the subject, header and footer.
$groupNamesToSkip = @("MyGroup1", "MyGroup2", "Department*") # TODO: modify me
# E-mail message settings
$to = "recipient@domain.com" # TODO: modify me
$subject = "List of groups user '%name%' has been removed from" # TODO: modify me
$reportHeader = "<b>User {0} has been removed from the following groups:</b><br/>" # TODO: modify me
$reportFooter = "<hr /><p><i>Please do not reply to this e-mail, it has been sent to you for notification purposes only.</i></p>" # TODO: modify me
function SkipGroup($patterns, $name)
{
foreach ($pattern in $patterns)
{
if ($name -like $pattern)
{
return $True
}
}
return $False
}
# Get the default Web Interface address
$webInterfaceAddress = "%adm-WebInterfaceUrl%"
if ([System.String]::IsNullOrEmpty($webInterfaceAddress))
{
$Context.LogMessage("Default web interface address not set for Adaxes service. For details, see http://www.adaxes.com/help/?HowDoI.ManageService.RegisterWebInterface.html", "Warning")
}
# Add link to user
$userGuid = [Guid]$Context.TargetObject.Get("objectGuid")
$reportHeader = [System.String]::Format($reportHeader, "<a href='$webInterfaceAddress`#/Browse/$userGuid'>%name%</a>")
# Get all groups user is a direct member of
$groupGuidsBytes = $Context.TargetObject.GetEx("adm-DirectMemberOfGuid")
# Get the Primary Group ID
$primaryGroupId = $NULL
if ($Context.TargetObject.DirectoryType -eq 1)
{
$primaryGroupId = $Context.TargetObject.Get("primaryGroupID")
}
$reportHeader += "<ol>"
foreach ($groupGuidBytes in $groupGuidsBytes)
{
# Bind to the group
$groupGuid = [Guid]$groupGuidBytes
$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)
# Add group to the report
$groupDisplayName = $Context.GetDisplayNameFromAdsPath($groupPath, $True)
$reportHeader += "<li><a href='$webInterfaceAddress`#/Browse/$groupGuid'>$groupDisplayName</a></li>"
}
$reportHeader += "</ol>"
# Build report
$htmlReport = $reportHeader + "<br/>Total remove groups:$totalRemovedGroups" + $reportFooter
# Send mail
$Context.SendMail($to, $subject, $NULL, $htmlReport)
Preserving List of Group Memberships
To preserve a list of group memberships for future reference, you can save them to a text file, for example. The following version of the script saves a list of groups for a user to a file specified by $filePath.
You can use value references (e.g. %username%) as a part of the file path. Before the script is executed, the value references will be replaced with the property values of the user. For example, if you specify the following: \\server\share\%username%.txt, and run the script on a user whose username is jdoe, the resulting path will be \\server\share\jdoe.txt.
$filePath = "\\server\share\%username%.txt" # TODO: modify me
# 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")
}
# Create a plain text report
$report = New-Object "System.Text.StringBuilder"
$report.Append("The user was removed from the following groups:")
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)
# Skip Primary Group
if ($group.DirectoryType -eq 1 -and
$group.Get("primaryGroupToken") -eq $primaryGroupId)
{
continue
}
# Remove user from the group
$group.Remove($Context.TargetObject.AdsPath)
# Add the group to the report
$report.AppendLine()
$report.Append($group.Get("name"))
}
# Create a new text
$file = New-Item -Path $filePath -ItemType File
# Save the report to the file
Add-Content $file $report.ToString()
this script works great, but I do not see the action in the logs.
How can it be modified so that the user being removed from each group is logged in the Adaxes logs?
Hello Manuel,
To pass the remove from group operation through Adaxes pipeline (trigger Business Rules and create a log record), replace this line in the script
$group = $Context.BindToObject($groupPath)
with the following
$group = $Context.BindToObjectEx($groupPath, $True)
As per our check, the script works just fine. For troubleshooting purposes, please, provide the exact script you are using with all the modifications you made. If you do not want to post the script here, please, email it at support@adaxes.com.
$groupNamesToSkip = @("mmsd.licensing-m365-g3.users") # TODO: modify me
# E-mail message settings
$to = "%adm-InitiatorEmail%" # TODO: modify me
$subject = "List of groups user '%name%' has been removed from" # TODO: modify me
$reportHeader = "<b>User {0} has been removed from the following groups:</b><br/>" # TODO: modify me
$reportFooter = "<hr /><p><i>Please save information for future employee reference.</i></p>" # TODO: modify me
function SkipGroup($patterns, $sAMAccountName)
{
foreach ($pattern in $patterns)
{
if ($sAMAccountName -like $pattern)
{
return $True
}
}
return $False
}
# Get the default Web Interface address
$webInterfaceAddress = "%adm-WebInterfaceUrl%"
if ([System.String]::IsNullOrEmpty($webInterfaceAddress))
{
$Context.LogMessage("Default web interface address not set for Adaxes service. For details, see http://www.adaxes.com/help/?HowDoI.ManageService.RegisterWebInterface.html", "Warning")
}
# Add link to user
$userGuid = [Guid]$Context.TargetObject.Get("objectGuid")
$reportHeader = [System.String]::Format($reportHeader, "<a href='$webInterfaceAddress`ViewObject.aspx?guid=$userGuid'>%name%</a>")
# Get all groups user is a direct member of
$groupGuidsBytes = $Context.TargetObject.GetEx("adm-DirectMemberOfGuid")
$totalRemovedGroups = $groupGuidsBytes.Length - 1
if ($totalRemovedGroups -eq 0)
{
$Context.LogMessage("This user is a member only the primary group", "Information")
return
}
# Get the Primary Group ID
$primaryGroupId = $Context.TargetObject.Get("primaryGroupID")
$reportHeader += "<ol>"
foreach ($groupGuidBytes in $groupGuidsBytes)
{
# Bind to the group
$groupGuid = [Guid]$groupGuidBytes
$groupPath = "Adaxes://<GUID=$groupGuid>"
$group = $Context.BindToObject($groupPath)
# Skip the Primary Group
if ($group.Get("primaryGroupToken") -eq $primaryGroupId)
{
continue
}
# Skip special groups
$sAMAccountName = $group.Get("sAMAccountName")
if (($groupNamesToSkip -ne $NULL) -and
(SkipGroup $groupNamesToSkip $sAMAccountName))
{
continue
}
# Remove user from the group
$group.Remove($Context.TargetObject.AdsPath)
# Add group to the report
$groupDisplayName = [Softerra.Adaxes.Utils.ObjectNameHelper]::GetObjectName($groupPath, "IncludeParentPath")
$reportHeader += "<li><a href='$webInterfaceAddress`ViewObject.aspx?guid=$groupGuid'>$groupDisplayName</a></li>"
}
$reportHeader += "</ol>"
# Build report
$htmlReport = $reportHeader + "<br/>Total remove groups:$totalRemovedGroups" + $reportFooter
# Send mail
$Context.SendMail($to, $subject, $NULL, $htmlReport)
Thank you for the provided script. We double-checked it and works just fine. Most probably, there is some unprintable character in your script that causes the issue. We recommend you to directly copy the script from this article (using the Copy button) into the script editor in Adaxes Administration console and modify the variables there.
Exception calling "GetEx" with "1" argument(s): "The 'BCFB057DCCBF1C4D8E43CA06386E5AFB' property cannot be found in the cache." Stack trace: at <ScriptBlock>, <No file>: line 19
Exception calling "Get" with "1" argument(s): "The '513' property cannot be found in the cache." Stack trace: at <ScriptBlock>, <No file>: line 22
Import-Module Adaxes is not required here as no cmdlets are used.
Did you make any changes to the script? If so, please, provide the exact script you are using.
The issue occurs because you are using Adaxes 2023. The old version of the scripts were not adapted for it. We updated all the three scripts accordingly. Please, clear browser cache, refresh the page and copy the script you need above.
Sorry for the confusion, but we are not sure we understand what exactly you need to achieve. Membership in rule-based groups is only controlled by the specified rules. There is no possibility to override the rule in any way including PowerShell.
If you are using Adaxes 2023 or later you can register your Azure AD domain in Adaxes. As a result, you will be able to natively manage all the Azure AD groups. As well, you will be able to use the script to remove users not only from on-premises AD groups, but also from cloud ones without adding any modifications.
If you register an Azure AD domain and a synchronized on-premises AD domain in Adaxes, synchronized users will only be counted once towards the license limit. As such, to avoid the violation, you can, for example, add all the guest accounts to the unmanaged list. To do so, use the following script from our repository: https://www.adaxes.com/script-repository/add-guest-users-located-in-specific-organizational-units-to-unmanaged-accounts-s683.htm.
The problem I see is that every time the script is run it goes through each account again and overwrites the output. So now I have a share full of text files that get overwritten with Domain Users since it's the only group not being removed.
Is there an elegant way to either skip the accounts that have already been cleaned or append the text files instead of overwriting them on subsequent script runs?
To achieve the desired, you can add the below code right after line $groupGuids = $Context.TargetObject.GetEx("adm-DirectMemberOfGuid").
Unfortunately, there is no such possibility.
"Multiple ambiguous overloads found for "GetObjectName" and the argument count: "2". Stack trace: at <ScriptBlock>, <No file>: line 71"
I've copied and pasted the new version shown above but I continue getting this error. When we get the email, it shows a numbered list with the number of groups the account was removed from, but every line is blank as far as the actual group names are concerned.
Any suggestions?
The error is expected as the method was deprecated. As you can see, neither of the scripts in the article has the method. Just pick the one you need.