Copying user accounts

The following code sample copies a user account.

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

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

# Bind to the target container
$targetContainerDN = "CN=Users,DC=domain,DC=com"
$targetContainer = $service.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("userPrincipalName", "ajones") # Username
$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 = $service.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 = $service.OpenObject($groupPath, $null, $null, 0)
        $group.Add($user.AdsPath)
    }
}

See also