Reference page: Active Directory – Sample Scripts (Excel/VBA)
How to create Security Group
Security Group object could be created within its container object – Organizational Unit. The example below is based on the assumption that we successfully retrieved an instance of Organizational Unit. An existing User Account will also be added to the newly created Security Group.
Note. You need to login as an authorized person to successfully execute the script.
' Domain: DEV.ENV.COM Dim sDomain, dvDC sDomain = "DEV.ENV.COM" dvDC = Split(sDomain, ".") ' Organizational Units ' Company01 - Active Directory Path: "dev.env.com/Main/Client/Company01" ' User Accounts ' User01 - belongs to Company01 ' Security Groups ' Group02 - new Security Group; will be created in Company01 Dim sGroupName, sUserPath sGroupName= "Group02" sUserPath = "cn=User01, ou=Company01, ou=Client, ou=Main, dc=dev,dc=env,dc=com" '1. Create Security Group boolRC = CreateGroup(objClientOU, objSecurityGroup) If Not boolRC Then 'error-handling goes here End If '2. Add the User to the Group objSecurityGroup.PutEx 3, "member", Array(sUserPath) 'Submit info back to Active Directory On Error Resume Next objSecurityGroup.SetInfo boolRC = (Err.Number <> 0) On Error GoTo 0 'Error-handling If boolRC Then sReturnMessage = "Failed to add the user to Security Group " & sGroupName End If
How to create new Security Group in Active Directory (Excel/VBA source code)
Note that we assume that we have a valid object instance in objOU.
If you build your own script
Depending on the scale of solution you implement you may want to refactor and expand the example presented below in order to exclude usage of global variables (sDomain, sGroupName, sUserPath, etc.) and provide reporting functionality (based on sReturnMessage).
Public Function CreateGroup(ByRef objOU, ByRef objGroup) Dim boolRC ' 'Create Security Group On Error Resume Next Set objGroup = objOU.Create("Group", "cn=" & sGroupName) boolRC = (Err.Number <> 0) On Error GoTo 0 'Error-handling If boolRC Then sReturnMessage = "Failed to create Security Group " & sGroupName CreateGroup = False Exit Function End If objGroup.Put "sAMAccountName", sGroupName 'Submit group name On Error Resume Next objGroup.SetInfo boolRC = (Err.Number <> 0) On Error GoTo 0 'Error-handling If boolRC Then sReturnMessage = "Failed to create Security Group " & sGroupName CreateGroup = False Exit Function End If ' CreateGroup = True End Function