Script Repository


Add user to specified groups

April 21, 2021
1319

The script adds a user to the groups whose names (Group Name (pre-Windows 2000)) are specified in the user property. Group names in the property must be separated by commas. To run the script, install Adaxes PowerShell Module for Active Directory on the computer where Adaxes service is running.

Edit Remove
PowerShell
Import-Module Adaxes

$propertyForGroupNames = "adm-CustomAttributeText1" # TODO: modify me

try
{
    $groupNames = ($Context.TargetObject.Get($propertyForGroupNames)).Split(",")
}
catch
{
    $Context.LogMessage("No groups specified.", "Warning") # TODO: modify me
    return
}

# Get user domain name
$domainName = $Context.GetObjectDomain("%distinguishedName%")

# Add user to groups
foreach ($groupName in $groupNames)
{
    try
    {
        Add-AdmGroupMember -Identity $groupName.Trim() -AdaxesService localhost -Members "%username%" -Server $domainName -ErrorAction Stop
    }
    catch
    {
        $Context.LogMessage("An error occurred while adding user to group $groupName. Error: " + $_.Exception.Message, "Error")
    }
}

# Clear group names property
$Context.TargetObject.Put($propertyForGroupNames, $NULL)
$Context.TargetObject.SetInfo()


Comments ( 2 )
avatar
Fachmi
Nov 24, 2021
Hello,

this script works perfectly to add user to group. As mentioned in the description it can take more than one group with separated comma. I found below condition;

1. If user has been assigned groupA in the adm-CustomAttributeText1 and then the value of adm-CustomAttributeText1 become GroupB. Now user will be member GroupA and GroupB. It didn't remove the membership of GroupA

2. If User has been assigned GroupA and GroupB in adm-CustomAttributeText1 and then we remove GroupA from adm-CustomAttributeText1, the membership will still GroupA and GroupB

How can the membership always follow the value from adm-CustomAttributeText1?
avatar
Support
Nov 24, 2021
Hello Fachmi,

This script is only used to add users to groups, nothing else. If you need to adjust group membership based on a property value, use the following script: https://www.adaxes.com/script-repository/update-group-membership-based-on-property-value-s570.htm.
Leave a comment

Related Scripts