Skip to content

Import AD users from CSV with PowerShell

There are times when you want to bulk import users into Active Directory. You already did an AD users export to CSV file. But, now you like to use that CSV file to import the users back into AD. The fastest and most excellent approach is to use PowerShell. In this article, you will learn how to import AD users from CSV with PowerShell.

Import AD users PowerShell script

The Import-ADUsers.ps1 PowerShell script will go through the CSV file and create AD users with the below information per user:

  1. Full name
  2. First name
  3. Last name
  4. Display name
  5. User logon name
  6. User principal name
  7. Street
  8. City
  9. State
  10. Postal Code
  11. Country
  12. Job Title
  13. Department
  14. Company
  15. Manager
  16. OU
  17. Description
  18. Office
  19. Telephone number
  20. Email
  21. Mobile
  22. Notes
  23. Account status

Note: The account will have the password set as P@ssw0rd1234. Change this to a different password in the PowerShell script.

How to import users into Active Directory from CSV file

Let’s go through the steps and bulk import Active Directory users from CSV file with PowerShell.

Step 1: Create CSV file with users

Without a CSV file, you can’t use the script and import the users into AD.

  • Suppose you don’t have an Active Directory to export the AD users to CSV file and only want a CSV file example so you can edit and use it; download the CSV file ImportADUsers.csv.
Import AD users from CSV with PowerShell CSV file

Step 2: Prepare import AD users PowerShell script

Download and place Import-ADUsers.ps1 PowerShell script on the Domain Controller C:\scripts folder. If you don’t have a scripts folder, create one.

Ensure the file is unblocked to prevent errors when running the script. Read more in the article Not digitally signed error when running PowerShell script.

Another option is to copy and paste the below code into Notepad. Give it the name Import-ADUsers.ps1 and place it in the C:\scripts folder.

<#
    .SYNOPSIS
    Import-ADUsers.ps1

    .DESCRIPTION
    Import Active Directory users from CSV file.

    .LINK
    alitajran.com/import-ad-users-from-csv-powershell

    .NOTES
    Written by: ALI TAJRAN
    Website:    alitajran.com
    LinkedIn:   linkedin.com/in/alitajran

    .CHANGELOG
    V2.00, 02/11/2024 - Refactored script
#>

# Define the CSV file location and import the data
$Csvfile = "C:\temp\ImportADUsers.csv"
$Users = Import-Csv $Csvfile

# The password for the new user
$Password = "P@ssw0rd1234"

# Import the Active Directory module
Import-Module ActiveDirectory

# Loop through each user
foreach ($User in $Users) {
    try {
        # Retrieve the Manager distinguished name
        $managerDN = if ($User.'Manager') {
            Get-ADUser -Filter "DisplayName -eq '$($User.'Manager')'" -Properties DisplayName |
            Select-Object -ExpandProperty DistinguishedName
        }

        # Define the parameters using a hashtable
        $NewUserParams = @{
            Name                  = "$($User.'First name') $($User.'Last name')"
            GivenName             = $User.'First name'
            Surname               = $User.'Last name'
            DisplayName           = $User.'Display name'
            SamAccountName        = $User.'User logon name'
            UserPrincipalName     = $User.'User principal name'
            StreetAddress         = $User.'Street'
            City                  = $User.'City'
            State                 = $User.'State/province'
            PostalCode            = $User.'Zip/Postal Code'
            Country               = $User.'Country/region'
            Title                 = $User.'Job Title'
            Department            = $User.'Department'
            Company               = $User.'Company'
            Manager               = $managerDN
            Path                  = $User.'OU'
            Description           = $User.'Description'
            Office                = $User.'Office'
            OfficePhone           = $User.'Telephone number'
            EmailAddress          = $User.'E-mail'
            MobilePhone           = $User.'Mobile'
            AccountPassword       = (ConvertTo-SecureString "$Password" -AsPlainText -Force)
            Enabled               = if ($User.'Account status' -eq "Enabled") { $true } else { $false }
            ChangePasswordAtLogon = $true # Set the "User must change password at next logon"
        }

        # Add the info attribute to OtherAttributes only if Notes field contains a value
        if (![string]::IsNullOrEmpty($User.Notes)) {
            $NewUserParams.OtherAttributes = @{info = $User.Notes }
        }

        # Check to see if the user already exists in AD
        if (Get-ADUser -Filter "SamAccountName -eq '$($User.'User logon name')'") {

            # Give a warning if user exists
            Write-Host "A user with username $($User.'User logon name') already exists in Active Directory." -ForegroundColor Yellow
        }
        else {
            # User does not exist then proceed to create the new user account
            # Account will be created in the OU provided by the $User.OU variable read from the CSV file
            New-ADUser @NewUserParams
            Write-Host "The user $($User.'User logon name') is created successfully." -ForegroundColor Green
        }
    }
    catch {
        # Handle any errors that occur during account creation
        Write-Host "Failed to create user $($User.'User logon name') - $($_.Exception.Message)" -ForegroundColor Red
    }
}
  • Line 21: Edit the CSV file location.
  • Line 25: Change password.

Step 3: Run import AD users PowerShell script

Run PowerShell as administrator and run the PowerShell script to import AD users from CSV file. Wait till it completes.

C:\scripts\.\Import-ADUsers.ps1

The script will show if:

  1. The user is created successfully.
  2. The user already exists.
  3. The user can’t be created with the error message.
A user with username Kylie.Davidson already exists in Active Directory.
A user with username Leonard.Clark already exists in Active Directory.
A user with username Madeleine.Fisher already exists in Active Directory.
A user with username Melanie.Scott already exists in Active Directory.
A user with username Nicholas.Murray already exists in Active Directory.
A user with username Piers.Bower already exists in Active Directory.
A user with username Ruth.Dickens already exists in Active Directory.
The user Sebastian.Nolan is created successfully.
The user Zoe.Roberts is created successfully.

Step 4: Verify AD users

Verify that the users are successfully created in Active Directory.

Import AD users from CSV with PowerShell ADUC

Read more: Add users to multiple groups with PowerShell »

Conclusion

You learned how to Import AD users from CSV with PowerShell. If you use the Export AD Users PowerShell script, and you want to import the users back into Active Directory, run the Import AD Users PowerShell script.

Did you enjoy this article? You may also like Export disabled users from Active Directory. Don’t forget to follow us and share this article.

ALI TAJRAN

ALI TAJRAN

ALI TAJRAN is a passionate IT Architect, IT Consultant, and Microsoft Certified Trainer. He started Information Technology at a very young age, and his goal is to teach and inspire others. Read more »

This Post Has 12 Comments

  1. Nice script, I used the export script first and was thinking to use this in order to bulk fill in missing AD-attributes for several users in Excel. But all users already exist in AD and the import script will skip these users and so not filling in the missing attributes?

    Regards,

    Marchel

  2. Hi. I performed the export and now I am performing the import.
    However, when creating new users it returns failure.
    WARNING: Failed to create user paulo.teste. The directory service was unable to allocate a relative identifier.
    Have you ever seen anything similar?

  3. This eventually worked…so THANK YOU VERY MUCH.!!
    I needed more understanding.
    The OU column needs FULL PATH.
    Those read backwards ..right to left. The last 2 items are your domain Name…
    so if it is PurpleSky.com……the last 2 items would be: “DC=PurpleSky, DC=com”
    Prior that are the OU’s and sub-OU’s
    So a full example of what should be in the OU column of the .csv is this:
    EXAMPLE:’ OU=Flower department. OU=VPN Users , OU=Company ,DC=BlueSky,DC=com

    Also..the GivenName populated the Full name.
    GivenName is the person’s First name in the profile properties of a SPECIFIC person.
    FULL NAME is the column on your main screen,,called “Name” when viewing an OU of users.
    I left that column blank but now it is populated.

    Can there be a powershell to bulk replace attributes, Such as the name…such as the Full Name field….replaced the single name with the 2 word formal name?

    My accounts created in the DISABLED state because I left the Accountstatus column empty.
    I believe I need to type “Enabled”

  4. So, get this…

    I just used this to import several thousand users.
    Worked well.

    EXCEPT FOR PEOPLE WITH A FIRST NAME “RON”!!
    They all failed, saying:
    “The password does not meet the length, complexity, or history requirement of the domain.”

    There was NO problem with the values for these “Ron” users.
    In fact, they WERE created, but they were disabled.
    (BUG #1)

    Here is what fixed the import issues:
    I had chosen a default password of “T0mk4Cronezbs!”
    The only thing I noticed was the text string “Ron” in the middle of the password.
    I laughed and said, “I wonder”, and I made the o zero in the password.
    “T0mk4Cr0nezbs!” instead of “T0mk4Cronezbs!”

    And they all imported – even the Rons!!!!
    (BUG #2) – and a BIZARRE ONE too.

    So,
    1) We need to trap that error better because they were created but disabled.
    2) The presence of the r o n sequence in the password is (somehow) a problem.

    How weird is that?!

    I wonder if I put other names in the password, it would also fail.

    EDIT/UPDATE:
    Yes, you cannot have any part of your name in a password since Windows 2000.

    We still need to trap that creation status, though, it’s not accurate. 🙂

    1. I tried it out, and you are correct.

      If you try to create the user “Ron Roberts” in AD GUI with the password “T0mk4Cronezbs!” or change the password to “T0mk4Cronezbs!”, you get the error that Windows cannot complete the password change. While this works for all the other users.

      Microsoft needs to look into this error and fix it.

      The account gets created with the script, but it will disable the account for security reasons because the password is not accepted.

  5. Looking to export home directory, and password as well. I imagine that’d be added in the Create List subsection, but entirely sure the syntax necessary. Figured I’d check here before winging it myself.

  6. Great, thanks a lot!
    Do you also have a script on how to delete users in bulk and remove their HOME and PROFILES folders? That what be just awesome.
    Best regards
    Tobias

Leave a Reply

Your email address will not be published. Required fields are marked *