PowerShell Script to Create Bulk Users from CSV File
Import-Csv 'users.csv' | ForEach-Object { New-ADUser -Name $_.Name -GivenName $_.GivenName -Surname $_.Surname -SamAccountName $_.SamAccountName -UserPrincipalName $_.UserPrincipalName -AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -Force) -Enabled $true } to create bulk users from a CSV file in PowerShell.Examples
How to Think About It
Algorithm
Code
Import-Csv 'users.csv' | ForEach-Object { $securePass = ConvertTo-SecureString $_.Password -AsPlainText -Force New-ADUser -Name $_.Name -GivenName $_.GivenName -Surname $_.Surname -SamAccountName $_.SamAccountName -UserPrincipalName $_.UserPrincipalName -AccountPassword $securePass -Enabled $true Write-Output "Created user: $($_.Name)" }
Dry Run
Let's trace creating user John Doe from CSV through the script
Read CSV line
Name=John Doe, GivenName=John, Surname=Doe, SamAccountName=jdoe, UserPrincipalName=jdoe@example.com, Password=Pass123!
Convert password
Convert 'Pass123!' to secure string
Create user
Call New-ADUser with user details and secure password
| Name | SamAccountName | Password (plain) | Password (secure) |
|---|---|---|---|
| John Doe | jdoe | Pass123! |
Why This Works
Step 1: Import CSV
The Import-Csv cmdlet reads the CSV file and converts each row into an object with properties matching the CSV headers.
Step 2: Convert Password
Passwords must be converted to a secure string using ConvertTo-SecureString to meet security requirements for user creation.
Step 3: Create User
The New-ADUser cmdlet creates a new Active Directory user with the provided details and enables the account.
Alternative Approaches
param([string]$CsvPath = 'users.csv') Import-Csv $CsvPath | ForEach-Object { if (-not $_.Password) { Write-Warning "Password missing for $($_.Name)"; return } $securePass = ConvertTo-SecureString $_.Password -AsPlainText -Force New-ADUser -Name $_.Name -SamAccountName $_.SamAccountName -AccountPassword $securePass -Enabled $true Write-Output "Created user: $($_.Name)" }
# DSC configuration example omitted for brevity; uses configuration to define users from CSV
Complexity: O(n) time, O(n) space
Time Complexity
The script processes each user once, so time grows linearly with the number of users in the CSV.
Space Complexity
Memory usage grows linearly with the number of users because all CSV data is loaded into memory.
Which Approach is Fastest?
Direct scripting with Import-Csv and ForEach-Object is fastest for simple bulk creation; DSC adds overhead but improves management.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Import-Csv + ForEach-Object | O(n) | O(n) | Simple, quick bulk user creation |
| Script with validation | O(n) | O(n) | Safer creation with error checks |
| PowerShell DSC | O(n) | O(n) | Declarative, repeatable user management |