👤 Bulk User Creation in Active Directory with PowerShell
Creating users manually in Active Directory is time-consuming and error-prone. This PowerShell script automates the entire process, including secure password generation, detailed logging, and CSV output — perfect for labs, onboarding, or testing environments. —✨ Key Features
- User and Password Generation:
- Creates a specified number of users (default: 10)
- Generates complex, secure passwords with a mix of uppercase, lowercase, numbers, and special characters
- Usernames follow a predictable pattern (e.g.,
User1,User2, etc.)
- Active Directory Integration:
- Uses the AD module to create all users in a specified Organizational Unit
- Validates that the target OU exists before attempting user creation
- Sets attributes like Department and Description
- CSV Output:
- Exports a CSV with
SamAccountName,UserPrincipalName,DisplayName,Password, and creation timestamp
- Exports a CSV with
- Logging:
- Writes timestamped entries to a log file
- Console output is color-coded: errors in red, warnings in yellow, successes in green
- Customization:
- Customizable parameters: user count, prefix, domain, password length, department
- Output paths for CSV and log files can be configured
📦 How to Use
Run the script with the required OU parameter:.\AD_Bulk_User_Creation.ps1 -TargetOU "OU=TestUsers,DC=domain,DC=com"Customize it with additional parameters:
.\AD_Bulk_User_Creation.ps1 -TargetOU "OU=TestUsers,DC=domain,DC=com" `
-UserCount 20 `
-UserPrefix "Employee" `
-Department "Sales" `
-PasswordLength 16
The script will:
– Create the specified number of users in the given OU
– Save all credentials to a CSV file
– Write a full log of actions and results
—
💻 Full Script
# Bulk User Creation in Active Directory with Passwords and Logging
# ----------------------------------------------------------------------
# This script generates a specified number of users in Active Directory with secure passwords,
# places them in a designated OU, exports credentials to CSV, and logs all activities.
# Import required module
Import-Module ActiveDirectory
# Script parameters
param (
[Parameter(Mandatory=$false)]
[int]$UserCount = 10,
[Parameter(Mandatory=$true)]
[string]$TargetOU,
[Parameter(Mandatory=$false)]
[string]$UserPrefix = "User",
[Parameter(Mandatory=$false)]
[string]$UserDomain = "yourdomain.com",
[Parameter(Mandatory=$false)]
[string]$Department = "IT",
[Parameter(Mandatory=$false)]
[int]$PasswordLength = 12,
[Parameter(Mandatory=$false)]
[string]$CsvOutputPath = ".\AD_Created_Users_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv",
[Parameter(Mandatory=$false)]
[string]$LogFilePath = ".\AD_User_Creation_Log_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
)
# Function to write to log file
function Write-Log {
param (
[string]$Message,
[string]$Level = "INFO"
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
switch ($Level) {
"ERROR" { Write-Host $logEntry -ForegroundColor Red }
"WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
"SUCCESS" { Write-Host $logEntry -ForegroundColor Green }
default { Write-Host $logEntry }
}
Add-Content -Path $LogFilePath -Value $logEntry
}
# Function to generate a random password
function New-RandomPassword {
param (
[int]$Length = 12
)
$Lowercase = 'abcdefghijklmnopqrstuvwxyz'
$Uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
$Numbers = '0123456789'
$SpecialChars = '!@#$%^&*()_-+={}[]<>?'
$Password = (Get-Random -Count 1 -InputObject $Lowercase.ToCharArray()) +
(Get-Random -Count 1 -InputObject $Uppercase.ToCharArray()) +
(Get-Random -Count 1 -InputObject $Numbers.ToCharArray()) +
(Get-Random -Count 1 -InputObject $SpecialChars.ToCharArray())
$AllChars = $Lowercase + $Uppercase + $Numbers + $SpecialChars
$Password += (Get-Random -Count ($Length - 4) -InputObject $AllChars.ToCharArray())
$Password = -join ($Password | Get-Random -Count $Password.Length)
return $Password
}
# Initialize credential storage
$UserCredentials = @()
# Begin script
try {
Write-Log "Script started. Creating $UserCount users in OU: $TargetOU"
try {
Get-ADOrganizationalUnit -Identity $TargetOU -ErrorAction Stop | Out-Null
Write-Log "Target OU validated: $TargetOU"
} catch {
Write-Log "Target OU does not exist or is invalid: $TargetOU" -Level "ERROR"
exit 1
}
for ($i = 1; $i -le $UserCount; $i++) {
$SamAccountName = "$UserPrefix$i"
$DisplayName = "$UserPrefix $i"
$UserPrincipalName = "$SamAccountName@$UserDomain"
$Password = New-RandomPassword -Length $PasswordLength
try {
if (Get-ADUser -Filter "SamAccountName -eq '$SamAccountName'" -ErrorAction SilentlyContinue) {
Write-Log "User $SamAccountName already exists. Skipping." -Level "WARNING"
continue
}
$UserParams = @{
SamAccountName = $SamAccountName
UserPrincipalName = $UserPrincipalName
Name = $DisplayName
DisplayName = $DisplayName
Path = $TargetOU
Department = $Department
Description = "Automatically generated user account"
Enabled = $true
ChangePasswordAtLogon = $true
AccountPassword = (ConvertTo-SecureString -String $Password -AsPlainText -Force)
}
New-ADUser @UserParams
Write-Log "Created user: $SamAccountName" -Level "SUCCESS"
$UserCredentials += [PSCustomObject]@{
SamAccountName = $SamAccountName
UserPrincipalName = $UserPrincipalName
DisplayName = $DisplayName
Password = $Password
CreationDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}
} catch {
Write-Log "Error creating user $SamAccountName. Error: $($_.Exception.Message)" -Level "ERROR"
}
}
if ($UserCredentials.Count -gt 0) {
$UserCredentials | Export-Csv -Path $CsvOutputPath -NoTypeInformation
Write-Log "Exported $($UserCredentials.Count) user credentials to $CsvOutputPath" -Level "SUCCESS"
} else {
Write-Log "No users were created successfully. CSV not generated." -Level "WARNING"
}
Write-Log "Script completed successfully. Created $($UserCredentials.Count) out of $UserCount users."
} catch {
Write-Log "Script execution failed. Error: $($_.Exception.Message)" -Level "ERROR"
} finally {
Write-Log "Script execution finished."
}
—
🛡️ Final Notes
- Test First: Always test in a non-production environment.
- Secure Files: The CSV contains passwords — protect or encrypt it appropriately.
- Use Cases: Ideal for labs, test migrations, or simulated onboarding flows.