Creating Test AD users with Powershell
Sometime last week on the Microsoft AD newsgroup, someone asked for a script to populate test users in Active Directory using a source text file with he user names and passwords. Of course, several people suggested VB scripts to do the task and Richard Mueller gave a pointer to an excellent script on his site.
Of course, I immediately started thinking of a way to do it PoSH style. The thinking, as always, was, "I bet Powershell can do this easier!"
The steps I came up with were:
1. Use Powershell to generate the csv ( I can even omit this step entirely and create the users on the fly)
2. Import the users into AD from the the csv
3. Enable the users
And here's my short PoSH script for the task:
#Create the csv and run in the headings
$outfilename = "out.csv"
"samAccountName,userPrincipalName,cn,sn,givenName,Password" | Out-File $outfilename -encoding ASCII
# Now, populate the csv for 500 users
for ($i = 1; $i -lt 500; $i++){
$samAccountName = "testUser" + "$i"
$userPrincipalName = 'testUser' + "$i" + '@example.com'
$cn = "testUser" + "$i"
$sn = 'example' + "$i"
$givenName = "testUser" + "$i"
$password = "password_123"
"$samAccountName, $userPrincipalName, $cn, $sn, $givenName, $password" | Out-File $outfilename -encoding ASCII -append
}
# Import the csv entries into AD as user objects
Import-Csv out.csv | ForEach-Object { New-QADuser -ParentContainer 'OU=test,DC=example,DC=com' -Name $_.samAccountName -samAccountName $_.samAccountName -userPrincipalName $_.userPrincipalName -FirstName $_.cn -LastName $_.sn -password $_.password }
# Enable the user objects
Get-QADUser -SearchRoot 'example.com/Test' | Set-QADuser -ObjectAttributes @{userAccountControl='512'}
# EASY!
This script compared to Richards, is an order of magnitude shorter and I think, easier to comprehend for almost anyone. It can also be extended, as I will still do to it, to require the number of users to be created to be entered as a variable, connection credentials for AD to be requested and the OU to create the users in as some other variable. Error checking can also be included to make it more shareable.