Creating user accounts in Active Directory can be time-consuming and error-prone, mainly when dealing with large numbers of users. Administrators can use PowerShell to automate importing user accounts into Active Directory from a CSV file to address this issue.
In this blog post, we will guide you through the steps involved in importing users into Active Directory from CSV using PowerShell. We will cover everything from preparing the CSV file with the necessary fields to running the PowerShell script and verifying the imported user accounts’ accuracy and completeness.
Whether you are an experienced Active Directory administrator or just getting started with PowerShell, this guide will provide a clear understanding of how to import users into Active Directory from CSV efficiently.
Table of Contents
Prerequisites
- Windows Active Directory Domain Controller. This tutorial uses Windows Server 2019, and the domain is theitbros.com.
- A code editor. This post will use Visual Studio Code.
- If you’re using a management computer (not the DC), make sure to install the Remote Server Administration Tool (RSAT).
Note. Check our tutorial on how to install and import PowerShell Active Directory module.
Prepare the CSV File
To begin importing users into Active Directory using PowerShell, we’ll need to create a CSV file with the user data. In this example, we’ll create a CSV file called “users.csv” with ten fictitious users and the following attributes: FullName, SN, GivenName, Company, Department, Title, TelephoneNumber, City, SAMAccountName, and Password.
Here’s an example of what the “users.csv” file might look like:
Name,SN,GivenName,Company,Department,Title,TelephoneNumber,City,SAMAccountName,UserPrincipalName,Password Brenda Thompson,Thompson,Brenda,Acme Inc,Marketing,Marketing Specialist,555-1234,New York City,bthompson,bthompson@theitbros.com,P@ssw0rd1 Eric Miller,Miller,Eric,Acme Inc,IT,IT Support Specialist,555-5678,Los Angeles,emiller,emiller@theitbros.com,P@ssw0rd2 Alexis Lee,Lee,Alexis,Acme Inc,HR,HR Manager,555-8901,Chicago,alee,alee@theitbros.com,P@ssw0rd3 Mark Martinez,Martinez,Mark,Acme Inc,Finance,Financial Analyst,555-2345,Houston,mmartinez,mmartinez@theitbros.com,P@ssw0rd4 Emily Adams,Adams,Emily,Acme Inc,Marketing,Marketing Manager,555-6789,San Francisco,eadams,eadams@theitbros.com,P@ssw0rd5 Thomas Johnson,Johnson,Thomas,Acme Inc,IT,IT Manager,555-0123,Seattle,tjohnson,tjohnson@theitbros.com,P@ssw0rd6 Maria Ramirez,Ramirez,Maria,Acme Inc,HR,HR Specialist,555-3456,Miami,mramirez,mramirez@theitbros.com,P@ssw0rd7 Steven Davis,Davis,Steven,Acme Inc,Finance,Senior Financial Analyst,555-7890,Atlanta,sdavis,sdavis@theitbros.com,P@ssw0rd8 Olivia Wilson,Wilson,Olivia,Acme Inc,Marketing,Marketing Coordinator,555-9012,Dallas,owilson,owilson@theitbros.com,P@ssw0rd9 Daniel Brown,Brown,Daniel,Acme Inc,IT,IT Director,555-2345,Boston,dbrown,dbrown@theitbros.com,P@ssw0rd10
Each row in the CSV file represents a single user, and commas separate the attributes for each user. Note that the password for each user is included in plain text, but we’ll use PowerShell to convert it to a secure string before importing the users into Active Directory.
Note. The values used are completely fictitious. In a real-world scenario, it’s important to use appropriate and secure passwords and not use easily guessable passwords like “password123” or “123456”.
Create the Script
Now that you have the CSV file containing the list of new AD users to create, it’s time we create the script to read it.
Create a new file called Import-ADUsersFromCSV.ps1 and open it in your code editor.
Once you’ve created the new script, copy the code below and paste it into your script.
# Import-ADUsersFromCSV.ps1 [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$CSVFile ) # Import the CSV file $users = Import-Csv -Path $CSVFile # Loop through each user in the CSV file foreach ($user in $users) { # Skip this user if any required attribute is empty if ([string]::IsNullOrEmpty($user.Name) -or [string]::IsNullOrEmpty($user.SamAccountName) -or [string]::IsNullOrEmpty($user.UserPrincipalName) -or [string]::IsNullOrEmpty($user.Password) -or [string]::IsNullOrEmpty($user.GivenName) -or [string]::IsNullOrEmpty($user.SN)) { Write-Host "Skipping user $($user.SamAccountName) because a required attribute is empty" continue } # Create the new user $newUserParams = @{ Name = $user.Name Surname = $user.SN GivenName = $user.GivenName DisplayName = $user.Name SamAccountName = $user.SamAccountName UserPrincipalName = $user.UserPrincipalName AccountPassword = ConvertTo-SecureString -String $user.Password -AsPlainText -Force ChangePasswordAtLogon = $true CannotChangePassword = $false PasswordNeverExpires = $false Enabled = $true } # Add non-required attributes, if they are not empty if (![string]::IsNullOrEmpty($user.Company)) { $newUserParams['Company'] = $user.Company } if (![string]::IsNullOrEmpty($user.Department)) { $newUserParams['Department'] = $user.Department } if (![string]::IsNullOrEmpty($user.Title)) { $newUserParams['Title'] = $user.Title } if (![string]::IsNullOrEmpty($user.TelephoneNumber)) { $newUserParams['OfficePhone'] = $user.TelephoneNumber } if (![string]::IsNullOrEmpty($user.City)) { $newUserParams['City'] = $user.City } try { New-ADUser @newUserParams Write-Host "Created user $($user.SamAccountName)" } catch { Write-Host "Failed to create user $($user.SamAccountName): $($_.Exception.Message)" } }
This PowerShell function code imports a CSV file containing user information, creates a new Active Directory (AD) user account for each row of the CSV file, and sets various attributes of the user account based on the values in the CSV file.
- The param block defines a single mandatory parameter $CSVFile, which is the path to the CSV file containing user information.
- The function then imports the CSV file using the Import-Csv cmdlet and stores the data in the $users variable.
- Next, the function loops through each user in the CSV file using a foreach loop. For each user, the function checks if any of the required attributes (Name, SamAccountName, UserPrincipalName, Password, GivenName, and SN) are empty. If any required attribute is empty, the function skips that user and outputs a message to the console.
- If all required attributes are present, the function creates a new user account in Active Directory using the New-ADUser cmdlet, with the attributes specified in $newUserParams. These attributes include the user’s name, last name, given name, display name, SamAccountName, UserPrincipalName, password, and various other settings such as whether the user must change their password at login and whether their password can be changed.
- The function also checks for non-required attributes such as Company, Department, Title, TelephoneNumber, and City in the CSV file and adds them to the $newUserParams hash table if they are not empty.
- If the creation of a user account fails, the function outputs an error message to the console.
Overall, this function provides a way to create multiple user accounts in Active Directory based on the data stored in a CSV file, saving time and effort compared to manually creating each user account.
Run the Script
Let’s now import users into Active Directory from csv using the script. Assuming the script is saved as Import-ADUsersFromCSV.ps1 and the CSV file users.csv is in the same directory as the script:
Type .\Import-ADUsersFromCSV.ps1 -CSVFile .\users.csv and press Enter. This will run the script and import the user accounts from the users.csv file. If the script execution was successful, you’d see a similar result to the image below.
Note: If you encounter an error when running the script, you may need to temporarily adjust the PowerShell execution policy by running the following command. This command allows the script to run on your system.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
Confirm the New Users
After importing new AD users using the script, let’s run another command to verify that the new users were indeed created. To do so, run the following code in PowerShell.
##Get-ADUsersFromCSV.ps1 # Read the properties names from the CSV except for Password. $properties = (Get-Content .\users.csv)[0].Split(",")[0..9] # Define a placeholder for the $users = [System.Collections.ArrayList]@() # Import the usercs.csv file and loop through each SamAccountName (Import-Csv .\users.csv).SamAccountName | ForEach-Object { try { # Get the AD user and retrieve specific properties $user = Get-ADUser -Identity $_ -Properties $properties -ErrorAction Stop | Select-Object $properties "Found user $_" | Out-Default $null = $users.Add($user) } catch { # Display the error is the command failed $_.Exception.Message | Out-Default } } # Display the list of users found in AD. $users | Format-Table
This PowerShell code does the following:
- Reads the first line of the CSV file “users.csv” in the current directory to retrieve the property names except for the “Password” property. The property names are stored in an array variable $properties.
- Defines an empty ArrayList object named $users that will store the retrieved user objects.
- Imports the CSV file “users.csv” and retrieves the SamAccountName column values using the Import-Csv cmdlet and the dot notation .SamAccountName.
- For each SamAccountName value, it attempts to retrieve the corresponding AD user object using the Get-ADUser cmdlet with the specified $properties and the ErrorAction Stop parameter to force an error if the command fails.
- If the AD user object is retrieved successfully, it is added to the $users array using the ArrayList.Add() method, and a message “Found user $_” is output to the console.
- If the command fails, the error message is output to the console.
- Finally, it outputs the $users array in a formatted table using the Format-Table cmdlet.
In summary, this PowerShell code retrieves specific properties of Active Directory users whose SamAccountName values are listed in the users.csv file and stores them in an ArrayList object $users. It also outputs messages for each successful retrieval and error messages for each failed retrieval. Finally, it displays the list of retrieved users in a formatted table.
The result would be similar to the screenshot below.
Conclusion
Importing users into Active Directory from CSV is a straightforward process that can save you a significant amount of time and effort when dealing with large numbers of users. By following the steps outlined in this guide, you can quickly and easily import user accounts into Active Directory using PowerShell
The process involves preparing the CSV file with the required fields, creating a PowerShell script, and running the script to import the user accounts. It is crucial to verify the imported user accounts’ accuracy and completeness before making them active in the Active Directory environment.
Additionally, the process can be extended to include additional user attributes, such as group membership, department, or title, to ensure that the imported users have all the necessary information for their accounts.
Overall, importing users into Active Directory from CSV is an excellent way to streamline user account management in Active Directory, improve efficiency, and reduce errors.
2 comments
Hello! Where does $User comes from in the 5th line of your script (ForEach ($User in $NewUsersList)) ?
May need to fix the script. Password variable is wrong. :)
Comments are closed.