Friday, 19 July 2013

Bulk import Users into AD from csv file

If you ever need to import a number of users into Active Directory, often the quickest and easiest way to do this is by using a csv file. If you can compile all the user's information into a csv file then importing that info into Active Directory is fairly straightforward if you use a bit of Powershell. This is a pretty basic example but it can always be tweaked to include more elements.

Part1:
Create a basic csv file which contains the info you need. In this example all we know about the users is their first and last name and what we want to set their password to. Thus our csv file looks like this:

name,firstname,Password
user1,robot,Passw0rd
user2,robot,Passw0rd
user3,robot,Passw0rd
user4,robot,Passw0rd
user5,robot,Passw0rd
user6,robot,Passw0rd
user7,robot,Passw0rd
user8,robot,Passw0rd
user9,robot,Passw0rd
user10,robot,Passw0rd

Be sure to save it as csv file and call it something simple, such as newusers.csv. Save it somewhere that is easy to access (C:\temp for example)

Part 2:
open notepad and paste the below info in.

Import-Module ActiveDirectory
$Users = Import-Csv -Delimiter "," -Path ".\newusers.csv"
foreach ($User in $Users)
{
$OU = "OU=RobotWorkers,OU=All Users,DC=rob,DC=local"
$Description = "Standard Robot User Account"
$Office = "Robotopolis City"
$Password = $User.password
$Detailedname = $User.name + "," + $User.firstname
$UserFirstname = $User.Firstname
$FirstLetterFirstname = $UserFirstname.substring(0,1)
$SAM = $FirstLetterFirstname + $User.name

New-ADUser -Name $Detailedname -SamAccountName $SAM -UserPrincipalName $SAM -DisplayName $Detailedname -Office $Office -Description $Description -GivenName $user.firstname -Surname $user.name -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path $OU
}

You need to check three things before you save the file,
1:that the delimiter is correct (open the csv file in notepad, are the words separated by commas?)
2:that the name of the .csv file is correct
3:that the OU it will create the user accounts in is correct

Once you've confirmed all of the above, click save. In the Save window navigate to the same folder as you saved the newusers.csv file (in this example that would be c:\temp), change the file type to All Files and call it something simple like newusersscript.ps1. Be sure to give it a PS1 extension!

Then open up Powershell, navgiate to the folder containing the files,

[PS] C:\users\adminbot> cd c:\temp <hit return>

Next you need to execute the script file but make sure to prefix it with .\

[PS] c:\temp> .\newusersscript.ps1 <hit return>

The powershell script should then run and populate AD with the new user accounts. With a bit of luck some new accounts will pop up in AD:




No comments:

Post a Comment