Copy AD accounts with PowerShell

Being able to copy AD accounts with one line of PowerShell code is probably my favorite feature of AD cmdlets RTM version.

Suppose you have an account the properties of which you would like to use to create another account? You probably want the new account to have a different name, password, etc. but it needs to have the same location, department and other attributes. The solution is extremely easy and straight-forward. You just need to do Get-QADUser for the sample account, and pipe into New-QADUser while specifying the new location and unique properties.

For example:

Get-QADUser 'James Johns' -export | New-QADUser -ParentContainer mydomain.local/test -Name 'Janny Grant' -SamAccountName jgrant -DisplayName 'Janny Grant' -FirstName Janny -LastName Grant -UserPassword 'J@nnysPwd' -import

One gotcha is that it will not copy the group membership, so you will have to use another oneliner for that:

(Get-QADUser 'James Johns').MemberOf | Add-QADGroupMember -Member ps64\jgrant

How cool is that? ;)

Tags: , , , , , ,

About these ads

39 Responses to “Copy AD accounts with PowerShell”


  1. 1 Xaegr January 10, 2008 at 5:02 pm

    Cool! :) Some time ago i wanted a Copy-QADObject cmdlet :)
    By the way – is New-QADObject cmdlet also allows pipeline input?

  2. 2 dmitrysotnikov January 10, 2008 at 5:12 pm

    Frankly, this was influenced by the copy account requests from you and other community members. ;)

    New-QADObject accepts pipeline but is less valuable because it does not have type-specific parameters and thus will not set a lot of the properties you might want to set.

  3. 3 matthew g January 11, 2008 at 5:41 pm

    You guys rock. i’m doing so much automation against our AD with the AD Cmdlets. It is allowing us to tackle some tasks that were just too cumbersome before.

    I upgraded to final release from beta on a machine. On both of them (one windows 2003 and one windows XP), I now get domain connection type errors.

    Get-QADUser : The specified domain either does not exist or could not be contacted. (Exception from HRESULT: 0x8007054B
    )
    At line:1 char:12

    i’ve resovled the error by stepping back to the beta version. I haven’t t-shot a lot, but figured I’d throw it out to you. Thanks, again! Thie product is absolutely awesome!

    Thanks,
    Matthew

  4. 4 dmitrysotnikov January 11, 2008 at 5:56 pm

    Matthew, unfortunately there is a number of other users who are facing the same issue. Please see this thread in the discussion forums: http://powergui.org/thread.jspa?threadID=5359&tstart=0

    What I would like you to do is email: Andrey.Moiseev at quest dot com – so he can send you a build which might fix the issue or will at least produce a detailed trace so we can troubleshoot.

    Thanks in advance and sorry for the inconvenience!

  5. 5 Rog June 3, 2008 at 8:46 am

    Hi!
    I tried this and i get this:

    cmdlet new-qaduser at command pipeline position 2
    Supply values for the following parameters:
    ParentContainer:

    so i enter the ou and get error msg:
    New-QADUser : The input object cannot be bound to any parameters for the command either because the command does not ta
    ke pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
    At line:1 char:37

    and i specify the parent container with -parentcontainer ‘ou=bla,dc=ble’ and i still get the same error msg What am i doing wrong?

    PS > get-qaduser ‘emir macak’|new-qaduser -name ‘Rog Ek’ -SamAcco
    untName jagrogek -DisplayName ‘Rog Ek’ -FirstName Rog -LastName Ek -userpassword ‘Ek1234′

  6. 6 dmitrysotnikov June 3, 2008 at 1:41 pm

    Rog,

    Unfortunately, this functionality was temporarily removed in 1.0.7 to mitigate one of the issues. It will be back in the 1.1 RTM coming soon – so please stay tuned.

    Dmitry

  7. 7 dmitrysotnikov June 3, 2008 at 1:43 pm

    You can obviously use ForEach-Object and manually list the properties you need to copy. E.g. (see the last two parameters for a way to copy attributes):

    get-qaduser ‘emir macak’ | foreach-object {
    new-qaduser -parentContainer mydomain.local/users -name ‘Rog Ek’ -SamAccountName jagrogek -DisplayName ‘Rog Ek’ -FirstName Rog -LastName Ek -userpassword ‘Ek1234′ -Title $_.Title -City $_.City
    }

  8. 8 Tamar Parm October 3, 2008 at 12:41 pm

    Hello Dmitry,

    I am using Management Shell for Active Directory version 1.12, but still getting error reported by Rog when trying to copy user. Do You have any idea why?

  9. 9 Dmitry Sotnikov October 3, 2008 at 2:17 pm

    Tamar,

    Can you try adding -export to the Get- command, and -import to the New-? Also, please specify the new parent container:

    Get-QADUser ‘James Johns’ -export | New-QADUser -ParentContainer mydomain.local/test -Name ‘Janny Grant’ -SamAccountName jgrant -DisplayName ‘Janny Grant’ -FirstName Janny -LastName Grant -UserPassword ‘J@nnysPass’ -import

    Dmitry

  10. 10 Tamar Parm October 8, 2008 at 7:19 am

    Thanks, now it works! :-)
    What -export and -import switches are for, anyway? I could not find them in cmdlet help.

    Tamar

  11. 11 Dmitry Sotnikov October 8, 2008 at 11:51 am

    Tamar,

    Oops, sorry for using aliases – these are SerializeValues/DeserializeValues

    Dmitry

  12. 12 Tamar Parm October 9, 2008 at 10:45 am

    Ok, thanks!

  13. 13 Rex March 27, 2009 at 8:17 pm

    is it possible to copy the password, also?

  14. 14 Dmitry Sotnikov March 29, 2009 at 9:58 pm

    Unfortunately, no. Passwords (even hashes) cannot be retrieved from AD with LDAP/ADSI/.NET and thus are not available through PowerShell either. If you need to migrate passwords as part of domain restructuring you might look into commercial AD migration tools (such as http://www.quest.com/migration-manager-for-active-directory/) which can indeed do that.

  15. 15 Rex April 2, 2009 at 2:50 pm

    your link is including the closing paren.

    What I’m looking for is a way to script a backup of a user object so that I can change the password, migrate exchange email, and then migrate the password back.

    Hmm. sounds like that just isn’t possible.

  16. 16 Dmitry Sotnikov April 2, 2009 at 9:25 pm

    Sorry for keeping recommending Quest products – I just happen to know them best – http://www.quest.com/recovery-manager-for-active-directory/ will be able to restore user backup to a previous value and this should be a cheaper option that full migration suite. Maybe you could even do the thing with a trial version – just don’t tell anyone that I mentioned that. ;)

  17. 17 Marco July 2, 2009 at 11:22 am

    Hello,

    I’m using version Active Roles Management Shell 1.2.2.1254

    According to the Help File I’m had to use curly braces to make it work:

    Get-QADUser ‘James Johns’ -export | %{New-QADUser -ParentContainer mydomain.local/test -Name ‘Janny Grant’ -SamAccountName jgrant -DisplayName ‘Janny Grant’ -FirstName Janny -LastName Grant -UserPassword ‘J@nnysPass’ -import}

    Marco

  18. 18 Marco July 8, 2009 at 11:10 am

    Hello again,

    just tried to copy a user account with an exchange mailbox that way – unfortunately without success:

    The exchange-typical attributes, like e.g. “Exchange-Features” are missing. Instead while copying the user manually (e.g. through dsa.msc) works fine.

    Even the first lines of the xml-files – I exported for testing – totally differ:
    (I changed realnames with , etc.)

    Original:
    =========

    ‘CN=<Mailbox- (),CN=,CN=InformationStore,CN=,CN=,CN= ,CN=,CN=,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=,DC=’

    Copy:
    =====

    //

    Any idea?

    tia,
    Marco

  19. 19 Marco July 8, 2009 at 11:11 am

    PS: The xml-copy into this thread obviously did not work ;-/

  20. 20 Dmitry Sotnikov July 13, 2009 at 9:22 am

    Marco,

    Please post the issue to http://powergui.org/forumindex.jspa?categoryID=55 and we’ll help you out! :)

    Dmitry

  21. 21 Michael.Fletcher@ercb.ca February 25, 2011 at 9:36 pm

    Dmitry;

    When trying to use the above example to copy a standard template user to create several IDs in our test lab I keep getting told the object already exists??? (If I recall the first one I tried seemed to work but when I tried to run a script to create more than one ID the error messages started popping up.

    I even went back to your example and tried to run it with minimal changes and I get the following:

    > Get-QADUser ‘-User-Template’ -export | New-QADUser -ParentContainer “OU=New Users,OU=-New Objects,dc=Testdomain” -Name ‘Janny Grant’ -SamAccountName jgrant -DisplayName ‘Janny Grant’ -FirstName Janny -LastName Grant -UserPassw
    ord ‘J@nnysPwd’ -import
    New-QADUser : The object already exists. (Exception from HRESULT: 0x80071392)
    At line:1 char:51
    + Get-QADUser ‘-User-Template’ -export | New-QADUser <<<< -ParentContainer "OU=New Users,OU=-New Objects,dc=Testdomain" -Name 'Janny Grant' -SamAccountName jgrant -DisplayName 'Janny Grant' -FirstName Janny -LastName Grant -UserPassword 'J@nnysPwd' -import
    + CategoryInfo : NotSpecified: (CN=Janny Grant,…gov,dc=ab,dc=ca:String) [New-QADUser], ObjectAlreadyExi
    stsException
    + FullyQualifiedErrorId : Quest.ActiveRoles.ArsPowerShellSnapIn.Powershell.Cmdlets.NewUserCmdlet

    Name Type DN
    —- —- —
    Janny Grant user CN=Janny Grant,OU=New Users,OU=-New Objects,dc=Testdomain
    It did create an account for Janny Grant (disabled) but din't copy anything from the template. Any ideas what I've got wrong.

    I'm running with full domain admin priviledges in the test lab.
    Active Roles Management Shell vers 1.4.0

  22. 22 Kristofer Olafsson May 7, 2011 at 1:47 am

    This also isn’t working properly for me.

    Get-QADUser ‘_USAccountingRole’ -export | New-QADUser -ParentContainer domain.com/usersou -Name ‘Janny Grant’ -SamAccountName jgrant -DisplayName ‘Janny Grant’ -FirstName Janny -LastName Grant -UserPassword ‘J@nnysPwd’ -import

    New-QADUser : The object already exists.

    At C:\Users\kolafsson\Documents\PS\create user.ps1:9 char:54
    + Get-QADUser ‘_USAccountingRole’ -export | New-QADUser <<<< -ParentContainer speckvc.com/usersou -Name 'Janny Grant' -SamAccountName jgrant -DisplayName 'Janny Grant' -FirstName Ja
    nny -LastName Grant -UserPassword 'J@nnysPwd' -import
    + CategoryInfo : NotSpecified: (CN=Janny Grant,…=speckvc,DC=com:String) [New-QADUser], ObjectAlreadyExistsException
    + FullyQualifiedErrorId : Quest.ActiveRoles.ArsPowerShellSnapIn.Powershell.Cmdlets.NewUserCmdlet

    Name Type DN
    —- —- —
    Janny Grant user CN=Janny Grant,OU=UsersOU,DC=domain,DC=com

    It creates the user but all the fields in AD are blank, the only field that is filled is the pre 2000 username… sAMAccountName is: $9SD000-DDRVTNP15P0M

    • 23 Dmitry Sotnikov May 7, 2011 at 2:06 am

      I think that unfortunately this direct copying is currently not supported in QAD cmdlets. Try to explicitly pass parameters in this syntax:

      Get-QADUser ‘_USAccountingRole’ | ForEach {

      New-QADUser -Department $_.Department

      }

      We need to revisit that old decision and see if we can bring the easier syntax back…

      • 24 Anonymous February 27, 2013 at 3:53 pm

        So essentially this post/method of copying user accounts via powershell doesn’t actually work. I always enjoy wasting an afternoon following a post that isn’t caveated to state that the example method doesn’t work, and you have to drill down into 30 plus comments to find out it isn’t supported by the cmdlets at all.

  23. 25 Kristofer Olafsson May 10, 2011 at 1:17 am

    Ok this worked, well enough.

    Get-QADUser ‘_USAccountingRole’ -export | Foreach {New-QADUser -ParentContainer domain.com/usersou -Name ‘Janny Grant’ -SamAccountName jgrant -DisplayName ‘Janny Grant’ -FirstName Janny -LastName Grant1 -UserPassword ‘J@nnysPwd’ -City $_.City -Department $_.Department -Description $_.Description -Company $_.Company -Fax $_.Fax -LogonScript $_.LogonScript -Manager $_.Manager -Office $_.Office -StateOrProvince $_.StateOrProvince -StreetAddress $_.StreetAddress -PostalCode $_.PostalCode -Title $_.Title -PhoneNumber $_.PhoneNumber -PostOfficeBox $_.PostOfficeBox -import }

    This only partially works it doesn’t create a User Longon name, but it does create the pre-windows 2000 name, some values are also not passed. Missing values are: Office, city and State, there could be more, my template profiles aren’t completely filled in.

    I wish passing the ParentContainer would work as I have few dozen OUs where a user could be. Get-QADUser ‘_USAccountingRole’ -export | Foreach {New-QADUser -ParentContainer $_.ParentContainer

  24. 26 Roccor January 4, 2012 at 10:54 pm

    What about creating a script using this code?

    $User = Read-Host “Enter the new user name”
    $Copy = Read-Host “Enter the user name to copy”
    $fname = Read-Host “Enter the new user’s first name”
    $lname = Read-Host “Enter the new user’s last name”
    $ou = Read-Host “Enter the destination OU container name”
    Read-Host “About to copy account $Copy and rename to $User”
    # copy specified AD account, create new account
    Get-QADUser $Copy | ForEach-Object {New-QADUser -ParentContainer difc.root01.org/people/employees/$ou -Name $fname $lname -SamAccountName $User -UserPassword ‘P@$$word1′ }

    I’m unable to get the -Name variables to be accepted. I tried enclosing them in ‘()’ but it printed the name as such: ‘($fname $lname)’

  25. 28 Lee Buskey.. March 7, 2012 at 10:54 pm

    [PS] H:\>New-QADUser -ParentContainer “OU=CDF2 Clients,OU=CDF2 Users,DC=CDF2,DC=usae,DC=now.com” -Name ‘joe blow ‘ -SamA
    ccountName joe.blow -DisplayName ‘Joe Blow’ -FirstName Joe -LastName Blow -UserPassword ‘ZAQ!2wsxZAQ!2wsx’
    New-QADUser : A referral was returned from the server. (Exception from HRESULT: 0x8007202B)
    At line:1 char:12
    + New-QADUser <<<

  26. 29 Dean Dahle July 26, 2012 at 3:17 pm

    Dmitry,

    Can you explain the process of you script a little for me? I’ve tried the first part, and it is working for me. But the second part is what I don’t particularly understand. the line, and what I don’t understand is……
    (Get-QADUser ‘James Johns’).MemberOf | Add-QADGroupMember -Member ps64\

    It’s the last part I don’t follow…. | Add-QADGroupMember -member ps64\jgrant

    As a related side note, can you comment or give a suggestion/idea for the following?

    Our old school way of creating accts was to copy templates using AD U&D. We have several templates, (8 or more in 3 domains) from which we create accounts. We might create 10 accounts a week accross those templates. Some templates are used a little and other alot. Aside form the domain, the group memberships are differant between all those templates.

    Do you have a suggestion on how to use a single PS script to create accounts regardless of the domain or at very least the template used to create the account? My ideal method is to create with one script, import account information from a csv file, and have the new user account created in the correct domain and OU, with the proper group memberships.

    With your script shown above, I could accomplish what I want, but I think I would need multiple scripts, (one for each template)

    Do you have any suggestions?

    Thank you,

    Dean

    • 30 Anonymous March 5, 2014 at 8:24 pm

      I had the same question and later discovered the “ps64″ part is just the domain name of the user you’re copy to.

  27. 31 erroneousgiant September 15, 2012 at 12:02 pm

    The copying of accounts from templates is ideal for what i need, we have around 3500 new users each year (i work in a college). What we are stuggling with is where users have them same name.

    We are trying to create users from a CSV which works as we can tell if a user is unique via their employeeID number but even though they are unique they
    Can have the same name. I have tried a nested if statement but it still can’t cope with aanother username being the same very well.

    Is there a way of after checking if a user is unique via a get-qaduser checking the employeeID, checking if a username exists and if it does creating username1 and so on. We have had instances of 10+ users having the same name which has caused problems

    Any help or advice would be amazing.

  28. 32 Jeff October 9, 2012 at 6:17 pm

    OK, so I’ve modified this in a way that should grab a number of different fields, but I keep getting the “A referral was returned from the server” error. Any ides?

    #get information
    $source = Read-Host ‘What account should be copied? (username)’
    $fn = Read-Host ‘New User First Name?’
    $mn = Read-Host ‘New User Middle Name?’
    $ln = Read-Host ‘New User Last Name?’
    $pw = Read-Host ‘New User Password?’
    $un = Read-Host ‘New User Username?’
    $pc = (Get-QADUser $source).parentcontainer
    #create account
    Get-QADUser $source -export | Foreach {New-QADUser -ParentContainer “$pc” -Name “$ln, $fn” -SamAccountName “$un” -DisplayName “$ln, $fn” -FirstName “$fn” -Initials “$mn” -LastName “$ln” -UserPassword “$pw” -City $_.City -Department $_.Department -Description $_.Description -Company $_.Company -LogonScript $_.LogonScript -Manager $_.Manager -Office $_.Office -import}
    (Get-QADUser $source).MemberOf | Add-QADGroupMember -Member “$un”

    • 33 Jeff October 9, 2012 at 8:04 pm

      fixed it. for those who want something that copies users, this should work everywhere as long as you update the UPN field. you can adjust the fields to copy over by adding/removing your own:

      #get information
      $source = Read-Host ‘What account should be copied? (username)’
      $fn = Read-Host ‘New User First Name?’
      $mn = Read-Host ‘New User Middle Name?’
      $ln = Read-Host ‘New User Last Name?’
      $pw = Read-Host ‘New User Password?’
      $un = Read-Host ‘New User Username?’
      $pc = (Get-QADUser $source).parentcontainer

      #create account
      Write-Host -foregroundcolor blue “Creating account….”
      Get-QADUser $source |ForEach-Object { New-QADUser -ParentContainer “$pc” -Name “$ln, $dr$fn” -SamAccountName “$un” -userprincipalname “$un@UPN” -DisplayName “$ln, $dr$fn” -FirstName “$fn” -Initials “$mn” -LastName “$ln” -UserPassword “$pw” -office $_.office -phonenumber $_.phonenumber -Description $_.Description -Company $_.Company -LogonScript $_.LogonScript -Title $_.Title -Department $_.Department -Manager $_.Manager -Notes $_.Notes -import} |Out-Null
      Write-Host -foregroundcolor blue “Account created.”

      #copy user groups
      Write-Host -foregroundcolor blue “Copying Member Of….”
      (Get-QADUser $source).MemberOf | Add-QADGroupMember -Member “$un” |Out-Null
      Write-Host -foregroundcolor blue “Groups copied.”

      Remove-Variable [a..z]* -Scope Global
      Remove-Variable [1..9]* -Scope Global
      Write-Host -foregroundcolor green “Finished.”

  29. 35 C-dric March 5, 2013 at 3:06 pm

    Hi there ! is there a way to copy attributes from one account to another ‘existing’ account ? The common point betwin the accounts is the same SAMAccountName but in different forests… your script seems to be so short and powerfull !

  30. 37 Anonymous August 14, 2013 at 2:55 pm

    It would be even cooler if you could copy the password as well…:)

    • 38 Dmitry Sotnikov August 16, 2013 at 10:21 am

      Unfortunately, I don’t think you can do this with PowerShell. There are AD migration tools that can migrate accounts with passwords.


  1. 1 Create new AD account similar to a current user - Admins Goodies Trackback on March 27, 2012 at 10:33 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




My Recent Tweets

Legal

The posts on this blog are provided “as is” with no warranties and confer no rights. The opinions expressed on this site are mine and mine alone, and do not necessarily represent those of my employer - WSO2 or anyone else for that matter. All trademarks acknowledged.

© 2007-2014 Dmitry Sotnikov

January 2008
M T W T F S S
« Dec   Feb »
 123456
78910111213
14151617181920
21222324252627
28293031  

Follow

Get every new post delivered to your Inbox.

Join 2,329 other followers

%d bloggers like this: