Skip to content

Copying user accounts

The following code sample copies a user account.

[Reflection.Assembly]::LoadWithPartialName("Softerra.Adaxes.Adsi")

# Connect to the Adaxes service
$admNS = New-Object "Softerra.Adaxes.Adsi.AdmNamespace"
$admService = $admNS.GetServiceDirectly("localhost")

# Bind to the target container
$targetContainerDN = "CN=Users,DC=domain,DC=com"
$targetContainer = $admService.OpenObject("Adaxes://$targetContainerDN",`
    $NULL, $NULL, 0)

# Copy user
$sourceUserPath = "Adaxes://CN=John Smith,OU=Sales,DC=domain,DC=com"
$newUserRdn = "CN=Ann Jones"
$user = $targetContainer.CopyHere($sourceUserPath, $newUserRdn)

$user.Put("givenName", "Ann") # First Name
$user.Put("sn", "Jones") # Last Name
$user.Put("sAMAccountName", "ajones") # User Logon Name (pre-Windows 2000)
$user.Put("unicodePwd", "secret") # Password
$user.Put("pwdLastSet", 0); # Must Change Password at First Logon
$user.SetInfo()

# Copy group membership

$groupGuids = New-Object "System.Collections.Generic.HashSet[System.Guid]"

$sourceUser = $admService.OpenObject($sourceUserPath, $NULL, $NULL, 0)

$userGroupGuids = $user.DirectMemberOf
$sourceUserGroupGuids = $sourceUser.DirectMemberOf

foreach ($userGroupGuid in $userGroupGuids)
{
    $groupGuids.Add($userGroupGuid) 
}

foreach ($sourceUserGroupGuid in $sourceUserGroupGuids)
{
    if (-not($groupGuids.Contains($sourceUserGroupGuid)))
    {
        $groupGuid = New-Object "System.Guid" (,$sourceUserGroupGuid)
        $groupGuid = $groupGuid.ToString("B")
        $groupPath = "Adaxes://<GUID=$groupGuid>"
        $group = $admService.OpenObject($groupPath, $NULL, $NULL, 0)
        $group.Add($user.AdsPath)
    }
}

See also