Import Users to AD form CSV

Hi There 

I need a guidance on how to import  uses into AD with the info from a CSV file the we received from HR. I am a newbie to scripting and powershell 

The CSV has all the Info of each learner: Name , Surname , Learner ID , School , Grade e.g.

We need to import the learners into AD OU based on the School and grade they are in.

It first need to check : Does the users exits, if true check what has changed like school and grade, if false create the user.

I believe that will work with some kind of variable mapping ?

I got this script that i want to use

Import-Module ActiveDirectory
# Get current directory and set import file in variable
$path     = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath  = $path + "\import_create_ad_users.csv"
# Define variables
$log      = $path + "\create_ad_users.log"
$date     = Get-Date
$i        = 0
# Change this to the location you want the users to be created in your AD
$location = "OU=Test,OU=Users,DC=hican,DC=nl"
# FUNCTIONS
Function createUsers
{
  "Created following users (on " + $date + "): " | Out-File $log -append
  "--------------------------------------------" | Out-File $log -append
  Import-CSV $newpath | ForEach-Object { 
    # A check for the country, because those were full names and need 
    # to be landcodes in order for AD to accept them. I used Netherlands 
    # as example
    If($_.CO -eq "Netherlands")
    {
      $_.CO = "NL"
    }
    # Replace dots / points (.) in names, because AD will error when a 
    # name ends with a dot (and it looks cleaner as well)
    $replace = $_.CN.Replace(".","")
    If($replace.length -lt 4)
    {
      $lastname = $replace
    }
    Else
    {
      $lastname = $replace.substring(0,4)
    }
    # Create sAMAccountName according to this 'naming convention':
    # <FirstLetterInitials><FirstFourLettersLastName> for example
    # hhica
    $sam = $_.Initials.substring(0,1).ToLower() + $lastname.ToLower()
    Try   { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" }
    Catch { }
    If(!$exists)
    {
      $i++
      # Set all variables according to the table names in the Excel 
      # sheet / import CSV. The names can differ in every project, but 
      # if the names change, make sure to change it below as well.
      $setpass = ConvertTo-SecureString -AsPlainText $_.Password -force
      New-ADUser $sam -GivenName $_.GivenName -Initials $_.Initials ` 
      -Surname $_.SN -DisplayName $_.DisplayName -Office $_.OfficeName `
      -Description $_.Description -EmailAddress $_.Mail ` 
      -StreetAddress $_.StreetAddress -City $_.L `
      -PostalCode $_.PostalCode -Country $_.CO -UserPrincipalName $_.UPN ` 
      -Company $_.Company -Department $_.Department -EmployeeID $_.ID ` 
      -Title $_.Title -OfficePhone $_.Phone -AccountPassword $setpass
 
      # Set an ExtensionAttribute
      $dn  = (Get-ADUser $sam).DistinguishedName
      $ext = [ADSI]"LDAP://$dn"
      $ext.Put("extensionAttribute1", $_.ExtensionAttribute1)
      $ext.SetInfo()
 
      # Move the user to the OU you set above. If you don't want to
      # move the user(s) and just create them in the global Users
      # OU, comment the string below
      Move-ADObject -Identity $dn -TargetPath $location
 
      # Rename the object to a good looking name (otherwise you see
      # the 'ugly' shortened sAMAccountNames as a name in AD. This 
      # can't be set right away (as sAMAccountName) due to the 20
      # character restriction
      $newdn = (Get-ADUser $sam).DistinguishedName
      Rename-ADObject -Identity $newdn -NewName $_.CN
 
      $output  = $i.ToString() + ") Name: " + $_.CN + "  sAMAccountName: " 
      $output += $sam + "  Pass: " + $_.Password
      $output | Out-File $log -append
    }
    Else
    {
      "SKIPPED - ALREADY EXISTS OR ERROR: " + $_.CN | Out-File $log -append
    }
  }
  "----------------------------------------" + "`n" | Out-File $log -append
}
# RUN SCRIPT
createUsers
#Finished

September 8th, 2015 8:43am

Hi,

What problems are you having? We can help you with specific questions, but it's unlikely someone will do a complete rewrite for you (especially since we don't have your input file or AD structure).

I'd skip that script entirely, as there's too much code for something this straightforward. Use this as an excuse to write something from scratch and let us know what problems you run into.

Free Windows Admin Tool Kit Click here and download it now
September 8th, 2015 8:53am

You need to decide on a standard for naming the users. Each user object will have a Name (also called the Common Name), which must be unique in the Organizational Unit or container. They will also have a "pre-Windows 2000 Logon Name", which is the value of the sAMAccountName attribute. This is limited to 20 characters and must be unique in the domain. Avoid commas, as they must be escaped in "Names" and are not allowed in sAMAccountNames.

You also need to decide where to locate the user objects. The default is the cn=Users container, but you can also create Organizational Units (OU's) and place them there. Or mayby you already have this structure setup.

September 8th, 2015 9:58am

Hi Richard

The CSV file we got form the HR system has the following columns.

DISTRICT

SCHOOL_NAME

GRADE

CLASS_NAME

LEARNER_ID

LAST_NAME

FIRST_NAME

So each learner has a unique learner ID that I can you as the samaccount name. it only has 13 numbers

To get the users imported I dont think we will have a problem into one OU

The ad structure will be as follows

Domain

Districts

Schools

                School name

                                                Grade

So the get the learners imported in to the specific school and grade based on the CSV file.

Also before creating the learner , check if the users exist , if they changed schools or grade it must move the learner to the correct ou.

I know if asking a lot of question , I just need to get an idea where to start.

Any assistance will be appreciated 

Free Windows Admin Tool Kit Click here and download it now
September 8th, 2015 12:33pm

hi 

ok i got the script working to import users to AD 

here is my script 

$Users = Import-Csv -Delimiter ";" -Path "C:\school_lan_tender_data1.csv"            
foreach ($User in $Users)            
{            
    $Displayname = $User.FIRST_NAME + " " + $User.LAST_NAME            
    $UserFirstname = $User.FIRST_NAME            
    $UserLastname = $User.LAST_NAME            
    $SAM = $User.CEMIS_LEARNER_ID            
    $UPN = $User.CEMIS_LEARNER_ID + "@" + $User.wcgschools.gov.za            
    $Description = $User.Description            
    $Password = $User.CEMIS_LEARNER_ID

if (Get-ADUser -F {SamAccountName -eq $SAM})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{

    New-ADUser -Name $SAM -DisplayName $Displayname -SamAccountName $SAM -UserPrincipalName $UPN -GivenName $UserFirstname -Surname $UserLastname -Description $Description -AccountPassword (ConvertTo-SecureString Password -AsPlainText -Force) -Enabled $true -Path "OU=NNBB,OU=NOD,OU=Districts,DC=wcgschools,DC=gov,DC=za" -ChangePasswordAtLogon $false PasswordNeverExpires $true -server WIN-U9CIR6N5AHB.wcgschools.gov.za            
}
 }

i now need to move the users into the "per school" OU

the school name is a column in the csv , so how do i based on that info move them to the correct ou ?

September 9th, 2015 7:58am

You could use a switch base on that info.

https://technet.microsoft.com/en-us/library/ff730937.aspx

If you ever did VBS before switch are a bit like CASE


Free Windows Admin Tool Kit Click here and download it now
September 9th, 2015 8:16am

That all depends on your OU structure.

I'd check the column and set a variable for the path you use in New-ADUser before you create the user. That way you never need to move the user and they just get created where they should end up.

September 9th, 2015 8:18am

Use the -Path parameter of the New-ADUser cmdlet to specify the distinguished name of the OU or container where the new object will be located. You can test your $User.School value and assign a variable for this in a Switch or If statement, or if the school is always the name of the OU, you can construct the value. Perhaps (in part):

$SchoolOU = "OU=" + $User.School + ",OU=NOD,OU=Districts,DC=wcgschools,DC=gov,DC=za"

New-ADUser -Path $SchoolOU ....

Then there is no need to move the user object later.
Free Windows Admin Tool Kit Click here and download it now
September 9th, 2015 9:08am

Following TechNet article might help you to achieve your script.

http://social.technet.microsoft.com/wiki/contents/articles/24541.powershell-bulk-create-ad-users-from-csv-file.aspx

September 10th, 2015 4:14pm

Hi C van Dyk,

if you decide to use my script, then at least leave my name in it as Author :)

Link to my script

My script is, like Mike already pointed out, too detailed for what you want to achieve. You only need a short basic script for that. you could use my script as a basis, but just remove all the 'difficult' non-essential stuff. You basically only need the foreach to loop through your csv and the New-ADUser Cmdlet to create the users.

As you already figured the creation part out, you could use something like this to move them to the correct OU:

$addn     = (Get-ADDomain).DistinguishedName
$dn       = Get-ADUser <SAM_NEWLY_CREATED_USER>
$location = "OU=$($_.GRADE),OU=$($_.SCHOOL_NAME),OU=Schools,$($addn)"

if ([adsi]::Exists("LDAP://$($location)"))
{
  Move-ADObject -Identity $dn -TargetPath $location
}
Note: I didn't test this, this is just from the top of my head to give you an idea.


Free Windows Admin Tool Kit Click here and download it now
September 11th, 2015 3:48am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics