Sunday, 20 April 2014

Create Bulk AD Users from CSV using Powershell Script

Creating Bulk AD Users in Active Directory is one of the important task for every Administrator either for testing or for set of actual new employees. Normally you can create new AD user using ADUC console. But it is time consuming job if you want create multiple ad users at the same time. To overcome this every administrator should rely on any of the script technology like VBScript and Powershell. In this article. I am going write and explain Powershell Script to Create Bulk AD Users from CSV.

Before proceed, please ensure that the Active Directory module for Windows Powershell is installed or not in your machine. It will be installed by default in Domain Controller. In client machines, you need to install it through Remote Server Administration Tools.
Use below command to check Active Directory module is installed or not:
Get-Module -Listavailable
Create Multiple AD Users from CSV using Powershell Script
If you are newbie to Powershell, don’t forget to set your Execution Policy to unrestricted or you might get an error when you try run the script. Use the below command to set your Execution Policy:
Set-ExecutionPolicy Unrestricted
Powershell Script to Create Bulk Active Directory Users from CSV

Powershell Script to Create Bulk AD Users from CSV file

   1. Consider the CSV file NewUsers.csv which contains set of New AD Users to create with the attributes Name, samAccountName and ParentOU.

Create Bulk AD Users from CSV file using Powershell Script
Note: The value of ParentOU should be enclosed with double quote ("). like "OU=TestOU,DC=TestDomain,DC=Local" since it has the special character comma (,). because in csv file the comma (,) is the key character to split column headers. (Ex file: Download NewUsers.csv).

   2. Copy the below Powershell script and paste in Notepad file.
   3. Change the NewUsers.csv file path with your own csv file path.
   4. Change the domain name TestDomain.local into your own domain name
   5. SaveAs the Notepad file with the extension .ps1 like Create-BulkADUsers-CSV.ps1

Click to download Powershell script as file Download Create-BulkADUsers-CSV.ps1
Import-Module ActiveDirectory
Import-Csv "C:\Scripts\NewUsers.csv" | ForEach-Object {
 $userPrincinpal = $_."samAccountName" + "@TestDomain.Local"
New-ADUser -Name $_.Name `
 -Path $_."ParentOU" `
 -SamAccountName  $_."samAccountName" `
 -UserPrincipalName  $userPrincinpal `
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true
Add-ADGroupMember "Domain Admins" $_."samAccountName";
}
   6. Now run the Create-BulkADUsers-CSV.ps1 file in Powershell to create Bulk Active Directory users from CSV file.
PS C:\Scripts> .\Create-BulkADUsers-CSV.ps1
Create Bulk Active Directory Users from CSV Powershell Script

Note: I have placed script file in the location C:\Scripts, if you placed in any other location, you can navigate to that path using CD path command (like cd "C:\Downloads").

   7. Now you can check the newly Created AD Users though ADUC console.

Powershell Script to Create Bulk AD Users from CSV file

Add more AD Attributes to New User:

Here, we have Created Bulk AD Users from CSV with only three attributes Name, samAccountName and ParentOU by CSV input. If you want to give more attributes from CSV input, you can add that attributes into csv file and change the above Powershell script accordingly.

Example: if you want to add EmailAddress to new user, your csv file should be like below file.

Create Bulk AD Users from CSV Powershell Script

Change the Powershell script like this:
Import-Module ActiveDirectory
Import-Csv "C:\Scripts\NewUsers.csv" | ForEach-Object {
 $userPrincinpal = $_."samAccountName" + "@TestDomain.Local"
New-ADUser -Name $_.Name `
 -Path $_."ParentOU" `
 -SamAccountName  $_."samAccountName" `
 -UserPrincipalName  $userPrincinpal `
 -AccountPassword (ConvertTo-SecureString "MyPassword123" -AsPlainText -Force) `
 -ChangePasswordAtLogon $true  `
 -Enabled $true `
 -EmailAddress $_."EmailAddress"
Add-ADGroupMember "Domain Admins" $_."samAccountName";
}


Refer this technet article http://technet.microsoft.com/en-us/library/ee617253.aspx to Create Bulk AD Users with more AD attributes.

Next: Export AD users to CVS using Powershell

Advertisements
Advertisements

29 comments:

  1. thanks it worked for me,but it does not gives first and second name?please let me know how to add the first name and second name.

    ReplyDelete
  2. Hi Morgan,

    Do we have additional commands if I will work via remote desktop using may APAC domain account.

    Thanks a lot..

    Erik

    ReplyDelete
  3. This was extremely helpful as we created a new domain. I exported the users from the old domain to a csv and cleaned up the information.(It was pretty bad) The powershell ISE was invaluable during the process.
    This is what I ended up using. If you don't assign managers then delete that line or all will fail.

    Import-Module ActiveDirectory
    Import-Csv "users.csv" | ForEach-Object {
    New-ADUser -Verbose `
    -Name $_."Name" `
    -Path $_."ParentOU" `
    -SamAccountName $_."samAccountName" `
    -UserPrincipalName $_."UserPrincipalName" `
    -AccountPassword (ConvertTo-SecureString "Password1" -AsPlainText -Force) `
    -ChangePasswordAtLogon ([System.Convert]::ToBoolean($_."ChangePasswordAtLogon")) `
    -Enabled $true `
    -EmailAddress $_."EmailAddress" `
    -CannotChangePassword ([System.Convert]::ToBoolean($_."CannotChangePassword")) `
    -Company $_."Company" `
    -Department $_."Department" `
    -Description $_."Description" `
    -DisplayName $_."DisplayName" `
    -Fax $_."Fax" `
    -GivenName $_."GivenName" `
    -HomeDirectory $_."HomeDirectory" `
    -HomeDrive $_."HomeDrive" `
    -HomePage $_."HomePage" `
    -HomePhone $_."HomePhone" `
    -Initials $_."Initials" `
    -Manager $_."Manager" `
    -Office $_."Office" `
    -OfficePhone $_."OfficePhone" `
    -PasswordNeverExpires ([System.Convert]::ToBoolean($_."PasswordNeverExpires")) `
    -ScriptPath $_."ScriptPath" `
    -City $_."City" `
    -State $_."State" `
    -StreetAddress $_."StreetAddress" `
    -Surname $_."Surname" `
    -Title $_."Title" `
    }

    I've already created a script to join all my computers to the new domain using the same technique.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Shannon Mitchell28 August 2014 at 11:40

    Quick question, have you used Excel or Access to create the CSV file?

    ReplyDelete
    Replies
    1. I just used notepad, but viewed in Excel to create screenshot that you are seeing in my article

      Delete
  6. Hey , how can I set the password for each user in the CSV?
    thx.

    ReplyDelete
  7. when I try to use Zach's script, I'm prompted to enter a "name" in Powershell? Anyone know what that is about? Complete powershell n00b here.

    ReplyDelete
    Replies
    1. Hi Patrick, pls send your complete powershell script to morgantechspace@gamil.com

      Delete
  8. When I run this code it has an error
    New-ADUser : Directory object not found
    At F:\CreateADUser\Create-BulkADUsers-CSV.ps1:4 char:1
    + New-ADUser -Name $_."Name" `
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (CN=TestUser,OU=...verDev,DC=Local:String) [New-ADUser], ADIdentityNotFo
    undException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
    icrosoft.ActiveDirectory.Management.Commands.NewADUser

    Can you help me fix it

    ReplyDelete
    Replies
    1. Can you post complete script here? or is it possible to send script to us (morgantechspace@gmail.com)

      Delete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Hello, when I run the basic script, I get the following error.

    New-ADUser : The object name has bad syntax
    At C:\Scripts\Create-BulkADUsers-CSV.ps1:3 char:1
    + New-ADUser -Name $_.Name `
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (CN=\"Sannidhira...XXXX,DC=com"
    :String) [New-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirec
    tory.Management.Commands.NewADUser

    Add-ADGroupMember : Cannot find an object with identity: 'susannid' under:
    'DC=sap,DC=XXXX,DC=com'.
    At C:\Scripts\Create-BulkADUsers-CSV.ps1:10 char:1
    + Add-ADGroupMember "Domain Admins" $_."samAccountName";
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (susannid:ADPrincipal) [Add-ADGr
    oupMember], ADIdentityNotFoundException
    + FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Micros
    oft.ActiveDirectory.Management.Commands.AddADGroupMember

    ReplyDelete
    Replies
    1. Can you post complete script here? or is it possible to send script and csv file to us (morgantechspace@gmail.com)

      Delete
  11. When I run the script from powershell, nothing happens it appears it runs but nothing happens does ANYone know why this may be? I dont receive an error or anything, I am pulling out my hair!!!!

    ReplyDelete
    Replies
    1. Hi qerkm, can you check whether have you copied the complete script or not.

      Delete
  12. hi Morgan, when I am creating the Bulk user with following script, I am getting an error, that server is not willing to process this request ?
    we have multiple DC here, does it matter ?
    or is it something I have no enough permission to create bulk users on DC ?

    ReplyDelete
    Replies
    1. Hi friend, multi-dc is not matter here..Can you post your script here? or is it possible to send script and csv file to us (morgantechspace@gmail.com)

      Delete
  13. Hey Morgan, I am trying to create a powershell script for Office 365 to send as multiple users. I have the single user script created but my multiple users send as is not working. Can you help with this?

    ReplyDelete
    Replies
    1. Hi Reggie, check out this article : http://www.morgantechspace.com/2016/01/set-send-as-permission-office-365-using-powershell.html to set send as permission.

      Delete
  14. I am trying the add AD users using powershell by importing the users from a csv. The problem I am having is, one of the users OU structure is different from the other users. Example: all users follow this OU structure (-Path ("OU=$DestinationOU,OU=$PC_Apple,$Users,OU=$Office,$Domain") and the rest use ("OU=$DestinationOU,OU=$Domain). Is there a way to use an IF statement in my script to so that if any of the information is not given for the first OU path, the second OU structure is used?

    Thank you,

    ReplyDelete
    Replies
    1. Yes, u can change your script like this:

      Import-Csv "C:\Scripts\NewUsers.csv" | ForEach-Object {
      $userPrincinpal = $_."samAccountName" + "@TestDomain.Local"

      $parentOU=$_."ParentOU"
      IF([string]::IsNullOrEmpty($parentOU)) {
      {
      $parentOU= 'OU=$DestinationOU,DC=$Domain'
      }

      New-ADUser -Name $_.Name `
       -Path  $parentOU `
       -SamAccountName  $_."samAccountName" `
       -UserPrincipalName  $userPrincinpal `
      }

      Delete
    2. Thanks Morgan. I tried what you suggested and I am getting the error below:

      New-ADUser : Cannot bind parameter because parameter 'Path' is specified more than once. To provide multiple values to param
      eters that can accept multiple values, use the array syntax. For example, "-parameter value1,value2,value3".
      At C:\Scripts\Reps.ps1:55 char:21
      + -Path <<<< "ParentOU" `
      + CategoryInfo : InvalidArgument: (:) [New-ADUser], ParameterBindingException
      + FullyQualifiedErrorId : ParameterAlreadyBound,Microsoft.ActiveDirectory.Management.Commands.NewADUser

      Delete
    3. Hi Morgan, I figured out why it was given me that error. I had two "-Path"'s. Now the second OU is giving some issues as it is trying to use the the first OU structure even after I have specified with the IF statement. Any thoughts? your assistance will be greatly appreciated. Thank you,

      Delete
    4. Hi, can you send ur script and csv file to us (morgantechspace@gmail.com)

      Delete
    5. Thank you, I have resolved the issue i was having with my script.

      Delete
  15. Thanks for this tutorial , i have freeipa server, and export all the user to text file ,i need to export this text file to windows server 2012 and i try that you mention but didn't work for me , please can you help me with that.
    BR.

    ReplyDelete
  16. Thanks for this tutorial .
    I have freeipa and export all user to text file , and i need to migrate this file to windows server 2012, i try that you mention but didn't work for me please can you help me with that,
    and you can see the text file result

    ---------------
    2 users matched
    ---------------
    User login: admin
    Last name: Administrator
    Home directory: /home/admin
    Login shell: /bin/bash
    UID: 1023400000
    GID: 1023400000
    Account disabled: False
    Password: True
    Kerberos keys available: True

    User login: booboo
    First name: boobs
    Last name: boobs
    Home directory: /home/booboo
    Login shell: /bin/bash
    Email address: booboo@elcld.net
    UID: 1023400003
    GID: 1023400003
    Account disabled: False
    Password: True
    Kerberos keys available: True
    ----------------------------
    Number of entries returned 2
    ----------------------------
    BR.

    ReplyDelete
    Replies
    1. You can read this post to export ad users to csv file : http://www.morgantechspace.com/2014/11/Export-AD-Users-to-CSV-using-Powershell.html

      Delete