将成员添加到组的示例代码

本主题包含将成员添加到组的代码示例。 Visual Basic Scripting Edition (VBScript) 和 C++ 示例会将表示成员的 IADs 对象添加到表示组的IADsGroup 对象,以添加成员。 Visual Basic .NET 和 C# 示例将修改表示组的 DirectoryEntry 对象的成员属性。

以下 C# 代码示例会将现有成员添加到组。 该函数采用组容器的 ADsPath,以及要添加到组的成员的可分辨名称。 ADsPath 用于创建表示组的 DirectoryEntry 对象。 PropertyValueCollection.Add 方法会将可分辨名称已传递给函数的成员添加到组。 接着,该函数使用 DirectoryEntry.CommitChanges 方法将新成员信息写入数据库。

使用以下参数调用该函数:

  • bindString:组容器的有效 ADsPath,例如“LDAP://fabrikam.com/CN=TestGroup,OU=TestOU,DC=fabrikam,DC=com”
  • newMember:要添加到组的成员的可分辨名称,例如“CN=JeffSmith,OU=TestOU,DC=fabrikam,DC=com”
private void AddMemberToGroup(

                                string bindString,

                                string newMember

                                )

{

    try
    {

        DirectoryEntry ent = new DirectoryEntry( bindString );

        ent.Properties["member"].Add(newMember);

        ent.CommitChanges();

    }

    catch (Exception e)
    {

        Console.WriteLine( "An error occurred.");

        Console.WriteLine( "{0}", e.Message);

        return;

    }

}

以下 Visual Basic .NET 代码示例会将现有成员添加到组。 该函数采用组容器的 ADsPath,以及要添加到组的成员的可分辨名称。 ADsPath 用于创建表示组的 DirectoryEntry 对象。 PropertyValueCollection.Add 方法会将可分辨名称已传递给函数的成员添加到组。 接着,该函数使用 DirectoryEntry.CommitChanges 方法将新成员信息写入数据库。

使用以下参数调用该函数:

  • bindString:组容器的有效 ADsPath,例如“LDAP://fabrikam.com/CN=TestGroup,OU=TestOU,DC=fabrikam,DC=com”
  • newMember:要添加到组的成员的可分辨名称,例如“CN=JeffSmith,OU=TestOU,DC=fabrikam,DC=com”
Private Sub AddMemberToGroup(ByVal bindString As String, 
                                      ByVal newMember As String)

    Try

        Dim ent As New DirectoryEntry(bindString)

        ent.Properties("member").Add(newMember)

        ent.CommitChanges()

    Catch e As Exception

        Console.WriteLine("An error occurred.")

        Console.WriteLine("{0}", e.Message)

        Return

    End Try

End Sub

以下 VBScript 示例会将现有成员添加到组。 该脚本会将用户 Jeff Smith 添加到 TestGroup 组。

Option Explicit

On Error Resume Next

Dim scriptResult        ' Script success or failure

Dim groupPath           ' ADsPath to the group container

Dim group               ' Group object

Dim memberPath          ' ADsPath to the member

Dim member              ' Member object

Dim groupMemberList     ' Used to display group members

Dim errorText           ' Error handing text

scriptResult = False

groupPath = "LDAP://fabrikam.com/CN=TestGroup,OU=TestOU,DC=fabrikam,DC=com"

memberPath = "LDAP://CN=JeffSmith,OU=TestOU,DC=fabrikam,DC=com"

WScript.Echo("Retrieving group object")

Set group = GetObject(groupPath)

If Err.number <> vbEmpty then

    Call ErrorHandler("Could not create group object.")

End If

Call ShowMembers(groupPath)     'Optional function call

WScript.Echo("Retrieving new member object")

Set member = GetObject(memberPath)

If Err.number <> vbEmpty then

    Call ErrorHandler("Could not get new member object.")

End If

WScript.Echo("Adding member to group.")

group.Add(member.ADsPath)

If Err.number <> vbEmpty then

    Call ErrorHandler("Could not add member to group.")

End If

Call ShowMembers(groupPath)     ' Optional function call

scriptResult = True

Call FinalResult(scriptResult)

'****************************************************************
' This function displays the members of a group. The function
' takes the ADsPath of the group.
'****************************************************************

Sub ShowMembers(groupPath)

    Dim groupMember

    Dim groupMemberList

    Dim groupObject

    Set groupObject = GetObject(groupPath)

    Set groupMemberList = groupObject.Members

    Select Case groupMemberList.Count

        Case 1 

            WScript.Echo vbcrlf & "The group has one member."

        Case 0

            WScript.Echo vbcrlf & "The group has no members."

        Case Else

            WScript.Echo vbcrlf & "The group has " & groupMemberList.Count & " members."

    End Select

    If groupMemberList.Count > 0 then

        WScript.Echo vbcrlf & "Here is a member list."

        For Each groupMember in groupMemberList

            WScript.Echo groupMember.Name

        Next

        WScript.Echo vbcrlf

    End If

    Set groupObject = Nothing

    Set groupMemberList = Nothing

End Sub

'****************************************************************
' This function shows if the script succeeded or failed. The 
' function processed the scriptResult variable.
'****************************************************************

Sub FinalResult(scriptResult)

    WScript.Echo vbcrlf

    If scriptResult = False then

        WScript.Echo "Script failed."

    Else

        WScript.Echo("Script successfully completed.")

    End If

    WScript.Quit

End Sub

'****************************************************************
' This function handles errors that occur in the script.
'****************************************************************

Sub ErrorHandler( errorText )

    WScript.Echo(vbcrlf & errorText)

    WScript.Echo("Error number: " & Err.number)

    WScript.Echo("Error Description: " & Err.Description)

    Err.Clear 

    Call FinalResult(scriptResult)

End Sub

以下 C++ 代码示例会将现有成员添加到组。

/////////////////////////////////////////////////////////////
/*  AddMemberToGroup() - Adds the passed directory object as a member 
                         of passed group
 
    Parameters
 
        IADsGroup * pGroup   - Group to hold the new IDirectoryObject.
        IADs* pIADsNewMember - Object which will become a member 
                               of the group. Object can be a user, 
                               contact, or group.
*/
HRESULT AddMemberToGroup(IADsGroup * pGroup, IADs* pIADsNewMember)
{
    HRESULT hr = E_INVALIDARG;
    if ((!pGroup)||(!pIADsNewMember))
        return hr;
 
    // Use the IADs::get_ADsPath() member to get the ADsPath.
    // When the ADsPath string is returned, to add the new
    // member to the group, call the IADsGroup::Add() member,
    // passing in the ADsPath string.
    // Query the new member for its AdsPath.
    // This is a fully qualified LDAP path to the object to add.
    BSTR bsNewMemberPath;
    hr = pIADsNewMember->get_ADsPath(&bsNewMemberPath); 
    if (SUCCEEDED(hr))
    {
 
        // Use the IADsGroup interface to add the new member.
        // Pass the LDAP path to the 
        // new member to the IADsGroup::Add() member
        hr = pGroup->Add(bsNewMemberPath);
 
        // Free the string returned from IADs::get_ADsPath()
        SysFreeString(bsNewMemberPath);
    }
    return hr;
}

将成员添加到域中的组

DirectoryEntry

DirectoryEntry.CommitChanges

IADs

IADsGroup

PropertyValueCollection.Add