6.15 Changing a User's Primary Group
You want to change the primary group of a user.
18.104.22.168 Using a graphical user interface
22.214.171.124 Using VBScript' This code first checks to see if the user's primary group is already ' set to the specified group. If not it will a) add the user to the group ' if not already a member and b) set the primary group id to the group. ' ------ SCRIPT CONFIGURATION ------ strUserDN = "<UserDN>" ' e.g. cn=rallen,ou=Sales,dc=rallencorp,dc=com strGroupDN = "<GroupDN>" ' e.g. cn=SalesGroup,ou=Sales,dc=rallencorp,dc=com ' ------ END CONFIGURATION --------- Const ADS_PROPERTY_APPEND = 3 set objUser = GetObject("LDAP://" & strUserDN ) WScript.Echo set objGroup = GetObject("LDAP://" & strGroupDN ) objGroup.GetInfoEx Array("primaryGroupToken"), 0 if objGroup.Get("primaryGroupToken") = objUser.Get("primaryGroupID") then WScript.Echo "Primary group for user already set to " & strGroupDN WScript.Quit end if intAddMember = 1 for each strMemberDN in objUser.GetEx("memberOf") if LCase(strMemberDN) = LCase(strGroupDN) then intAddMember = 0 Exit for end if next if intAddMember > 0 then objGroup.PutEx ADS_PROPERTY_APPEND, "member", Array(strUserDN) objGroup.SetInfo WScript.Echo "Added " & strUserDN & " as member of " & strGroupDN end if objUser.Put "primaryGroupID", objGroup.Get("primaryGroupToken") objUser.SetInfo WScript.Echo "Changed primary group id of " & strUserDN & _ " to " & objGroup.Get("primaryGroupToken")
The primary group is a holdover from Windows NT that was used to support Macintosh and POSIX clients, but it is not used actively in Active Directory. That said, you might have some legacy applications that depend on the primary group, and therefore, you may have to change some users' primary group.
Changing the primary group is not difficult, but it is not straightforward either. The primary group is stored on user objects in the primaryGroupID attribute, which contains the RID of the primary group. You can obtain this value by querying the primaryGroupToken attribute on the target group object. Before you can set the primaryGroupID on the user object, you have to first make sure the user is a member of the group. If you try to set the primaryGroupID for a group in which the user is not a member, you will get an error.
The default primaryGroupID is set to 513 (Domain Users) for all users.
6.15.4 See Also
Recipe 7.8 for determining the group name given a group ID, MS KB 297951 (HOWTO: Use the PrimaryGroupID Attribute to Find the Primary Group for a User), MS KB 321360 (How to Use Native ADSI Components to Find the Primary Group), and MS KB 243330 (Well Known Security Identifiers in Windows 2000)