By David Wiseman (Administrator)Created 13 May 2012, Modified 20 May 2012
My Rating:
Vote
Rating:
Not Rated
Views:12757
Downloads:50
Source:

Creating a large number of test Active Directory users with PowerShell

Language:  PowerShell

Compatibility

Windows XP Unknown Windows 2003 Unknown
Windows 2000 No Windows NT No
Vista Unknown Windows 2008 Yes
Description

How to create a large number of AD user accounts using PowerShell.


Notes
After re-building my test Active Directory domain I needed a way to create a large number of user accounts.  Previously I would have used VBScript or my Account Management Spreadsheet, but this time I decided to use PowerShell - more as a learning exercise for myself than anything else.  
 
The requirements for the script is that it must be able to generate an arbitrary number of user accounts in a specified organizational unit.  The usernames are generated in the format firstname.surname with a number used as a uniquefier in the case of a name collision.
 
To generate accounts using real names instead of a more synthetic name like P000123, we need a data source that we can use to generate random names from.  After a quick google search I came up with:
http://www.census.gov/genealogy/names/dist.male.first
http://www.census.gov/genealogy/names/dist.female.first
http://www.census.gov/genealogy/names/dist.all.last
 
To get started, copy the contents of the above URLs into files called "MaleFirstNames.txt", "FemaleFirstNames.txt" and "LastNames.txt".  This will give us a source of male & female first names and surnames that we can use to generate fictitious user names.  The script will process these files to extract only the names.
 
To create the user accounts, save the script as "CreateUsers.ps1" in the same folder as the text files created earlier.  You can then create user accounts using the following command (Change the bold text as required):
 
./CreateUsers -Path "ou=Sales,ou=All Users,dc=wisesoft,dc=local", -NumUsers 1000
 
So we can create an arbitrary number of user accounts in any particular OU with realistic names, but what if we want to populate our domain with user accounts in a number of different organizational units?
 
I decided to create a second script that will take a comma-separated list of OUs, department names and number of users to create.  The CSV file might look similar to this:
 
Path,NumUsers,Department
"ou=Sales,ou=MyUsers,dc=wisesoft,dc=local",500,"Sales"
"ou=Marketing,ou=MyUsers,dc=wisesoft,dc=local",50,"Marketing"
 
The sample above would be used to create 500 users in the Sales OU and 50 users in the Marketing OU.  If the Sales and Marketing OUs didn't exist, the script would attempt to create them.  Simply save the csv file as "ADImport.csv" and run the "Script2" powershell script below.  Note: You will need to save the other script as "CreateUsers.ps1" and create the MaleFirstNames.txt, FemaleFirstNames.txt and LastNames.txt text files as described above.
 
Script2:
  1. # Function to create OU if it doesn't already exist  
  2. function createOU($path){  
  3.     if ([ADSI]::Exists("LDAP://$path")){  
  4.         return  
  5.     }  
  6.     else  
  7.     {  
  8.         # Convert path to ou.    
  9.         # e.g. "ou=Sales,ou=my users,dc=wisesoft,dc=local" to "ou=Sales"  
  10.         $ou = $path.Substring(0,$path.IndexOf(","))  
  11.         # Get parent ou/container e.g. "ou=my users,dc=wisesoft,dc=local"  
  12.         $parent = $path.Substring($ou.Length+1,$path.Length-$ou.Length-1)  
  13.         # Check if parent container exists and create it if required  
  14.         if ([ADSI]::Exists("LDAP://$parent") -eq $false){  
  15.             createOU($parent)  
  16.         }  
  17.         "Creating $ou in $parent"  
  18.         $objParent = [ADSI]"LDAP://$parent"  
  19.         #Create OU  
  20.         $objOU = $objParent.Create("OrganizationalUnit",$ou)  
  21.         $objOU.SetInfo()  
  22.     }  
  23. }  
  24. <#  Expects CSV file called "ADImport.csv" with "Path", NumUsers" and "Department" headers.  
  25.  e.g.  
  26. Path,NumUsers,Department  
  27. "ou=Sales,ou=MyUsers,dc=wisesoft,dc=local",500,"Sales"  
  28. "ou=Marketing,ou=MyUsers,dc=wisesoft,dc=local",50,"Marketing"  
  29.  
  30. #>  
  31. Import-Csv ADImport.csv | ForEach{  
  32.     $path = $_.Path  
  33.     $NumUsers = $_.NumUsers  
  34.     $Department = $_.Department  
  35.     createOU($path)  
  36.     "Creating $NumUsers in path $path..."  
  37.     ./CreateUsers -Path $path -NumUsers $NumUsers -Department $Department  
  38. }  

* Requires CreateUsers.ps1 script below.

 
Code

Line Numbers: On  Off      Plain Text
<#
Example:
./CreateUsers -Path ou=Sales,ou=My Users,dc=wisesoft,dc=local -NumUsers 500

Requirements:
MaleFirstNames.txt
	- Text file containing a list of male first names
	http://www.census.gov/genealogy/names/dist.male.first
FemaleFirstNames.txt
	- Text file containing a list of female first names
	http://www.census.gov/genealogy/names/dist.female.first
LastNames.txt
	- Text file containing a list of surnames
	http://www.census.gov/genealogy/names/dist.all.last


#>
param(
	[Parameter(Mandatory=$true)]
	[int]$numusers,
	[Parameter(Mandatory=$true)]
	[string]$path,
	[string]$Department,
	[System.DateTime]$AccountExpirationDate,
	[string]$AccountPassword,
	[bool] $ChangePasswordAtLogon=$true,
	[string]$City,
	[string]$Company,
	[string]$Country,
	[string]$Description,
	[string]$Division,
	[bool]$Enabled=$true,
	[string]$Office,
	[string]$Organization
)
Import-Module ActiveDirectory
[Reflection.Assembly]::LoadWithPartialName("System.Web") 
Add-Type -AssemblyName Microsoft.VisualBasic

# Load a list of male names.  Remove all text after first space and convert to proper case
Write-Host "Loading Male first names...."
$MaleNames = Get-Content "MaleFirstNames.txt" | ForEach-Object{ 
	$name = $_
	If ($name.IndexOf(" ") -ge 0) {
		$name = $name.Substring(0,($name.IndexOf(" ")))
	}
	$name = [Microsoft.VisualBasic.Strings]::StrConv($name,'ProperCase')
	$name
}
# Load a list of female names.  Remove all text after first space and convert to proper 
Write-Host "Loading Female first names...."
$FemaleNames = Get-Content "FemaleFirstNames.txt" | ForEach-Object{ 
	$name = $_
	if ($name.IndexOf(" ") -ge 0) {
		$name = $name.Substring(0,($name.IndexOf(" ")))
	}
	$name = [Microsoft.VisualBasic.Strings]::StrConv($name,'ProperCase')
	$name
}
# Load a list of surnames.  Remove all text after first space and convert to proper 
Write-Host "Loading Surnames names...."
$Surnames = Get-Content "LastNames.txt" | ForEach-Object{ 
	$name = $_
	if ($name.IndexOf(" ") -ge 0) {
		$name = $_.Substring(0,($name.IndexOf(" ")))
	}
	$name = [Microsoft.VisualBasic.Strings]::StrConv($name,'ProperCase')
	$name
}
# Function to generate a random female name
Function GetRandomFemaleName(){
	$random = Get-Random -Minimum 0 -Maximum ($FemaleNames.Count)
	return $FemaleNames.GetValue($random)
}
# Function to generate a random male name
Function GetRandomMaleName(){
	$random = Get-Random -Minimum 0 -Maximum ($MaleNames.Count)
	return $MaleNames.GetValue($random) 
}
# Function to generate a random surname
Function GetRandomSurname() {
	$random = Get-Random -Minimum 0 -Maximum ($Surnames.Count)
	return $Surnames.GetValue($random)
}
# Password supplied via command line
if ($AccountPassword.Length -gt 0){
	$password=$AccountPassword
	#Password needs to be converted to a secure string type for New-ADUser
	$passwordss = ConvertTo-SecureString -AsPlainText $password -Force
}

for ($i = 0; $i -lt $numusers; $i++) {
	# Even distribution of male/female names are used
	if (($i % 2) -eq 0){
		$givenName = GetRandomMaleName
	}
	else {
		$givenName = GetRandomFemaleName
	}
	$sn = GetRandomSurname
	$displayName="$givenName $sn"
	$sAMAccountName="$givenname.$sn"
	$sAMAccountName = $sAMAccountName.Substring(0,[System.Math]::Min($sAMAccountName.Length,20))
	# Generate a random password if not supplied via the command line
	if ($AccountPassword.Length -eq 0)
	{
		$password = [System.Web.Security.Membership]::GeneratePassword(20,2)
		#Password needs to be converted to a secure string type for New-ADUser
		$passwordss = ConvertTo-SecureString -AsPlainText $password -Force
	}
	
	$retryCount =0
	do{
		# Loop will be exited unless an account with the same name already exists (in which it will retry with a uniquefier)
		$completed=$true
		$cn = $sAMAccountName
		$email = "$sAMAccountName@$env:USERDNSDOMAIN"
		Write-Host "Creating user"($i+1)"of $numusers.....$sAMAccountName | Password: $password"
		
		try{
			New-ADUser -sAMAccountName $sAMAccountName -Name $cn -DisplayName $displayName -givenName $givenName -Surname $sn `
						-Path $path -Enable $Enabled -AccountPassword $passwordss -Department $department `
						-AccountExpirationDate $AccountExpirationDate -ChangePasswordAtLogon $ChangePasswordAtLogon `
						-City $City -Company $Company -Country $Country -Description $Description -Division $Division `
						-EmailAddress $email -Office $Office -Organization $Organization
		}
		catch [Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException]
		{
			# Failed to create user because an account with the same name already exists.
			# Add a number to the account name to make it unique, increasing the number with each retry
			"Unable to create user '$sAMAccountName' as the user already exists. "
			$sAMAccountName=$sAMAccountNameOriginal
			$retryCount +=1
			# Ensure new length won't exceed maximum account name length of 20.
			if (($sAMAccountName.Length + ([string]$retryCount).Length) -gt 20) {
				$sAMAccountName = $sAMAccountName.Substring(0,$sAMAccountName.Length-([string]$retryCount).Length)
			}
			# append sAMAccountName with a uniquefier 
			$sAMAccountName = $sAMAccountName + $retryCount
			$completed=$false #Don't exit loop
			"Retrying with $sAMAccountName..."
		}
	} until ($completed)
	
}

 


Got a useful script? Click here to upload!


 

  Post Comment
Order By:  
User Comments
      
xiaoou
Posted On: 10/4/2018 3:32:16 AM

20181004 xiaoou stussy hoodie tory burch outlet online reebok shoes ugg boots clearance coach outlet online longchamp outlet store polo ralph lauren swarovski outlet store reebok shoes football shirts coach outlet online swarovski jewellery canada goose outlet puma shoes mulberry uk michael kors outlet mlb jerseys moncler jackets canada goose outlet store kobe shoes cheap ray ban sunglasses longchamp handbags true religion outlet uk christian louboutin shoes tods outlet online pandora charms sale clearance burberry outlet sale true religion jeans ugg boots clearance canada goose jackets uggs outlet canada goose jackets polo ralph lauren polo ralph lauren burberry canada cheap ray ban sunglasses canada goose jackets coach outlet online mlb jerseys ugg boots clearance kate spade outlet online michael kors outlet online adidas yeezy boost barbour women jackets canada goose jackets sale van cleef arpels jewelry cheap nhl jerseys michael kors outlet online cheap football shirts ray ban sunglasses outlet coach outlet online longchamp outlet online mizuno shoes asics running shoes ralph lauren polo ugg canada ferragamo shoes polo outlet factory store mont blanc outlet jordan 12 kd shoes bvlgari outlet canada goose coats nike air huarache cheap ugg boots ferragamo shoes canada goose outlet cheap jordan shoes coach factory outlet coach outlet nike outlet online nfl jerseys polo ralph lauren outlet true religion jeans ugg outlet uggs outlet uggs outlet supreme t shirts ralph lauren shirts cheap jordan shoes christian louboutin shoes true religion jeans sale kobe 9 elite coach outlet online coach outlet store pandora outlet nike outlet store coach outlet jordan 4 michael kors outlet online converse shoes sale cheap jordan shoes nfl jersey wholesale tory burch outlet online uggs outlet ugg boots clearance michael kors outlet christian louboutin shoes adidas nmd runner moncler coats coach outlet store online michael kors outlet clearance canada goose jackets nike shoes outlet christian louboutin shoes supreme t shirts ugg outlet michael kors outlet online air max 90 moncler jackets michael kors outlet clearance oakley sunglasses wholesale balenciaga shoes ugg boots clearance nike air max 1 ralph lauren uk denver broncos jersey ralph lauren polo coach outlet prada sunglasses for women coach factory outlet ugg outlet stores cheap ugg boots michael kors outlet swarovski outlet store cheap oakley sunglasses jordan shoes montblanc pens outlet nike air max soccer jerseys wholesale michael kors wallets for women ugg outlet michael kors bags nike roshe run chrome hearts online store ralph lauren polo michael kors outlet online ugg outlet canada goose outlet giuseppe zanotti shoes chrome hearts outlet store soccer cleats swarovski jewelry cheap oakley sunglasses canada goose outlet store fitflops shoes pandora jewelry hermes outlet store michael kors outlet online polo ralph lauren shirts canada goose coats ralph lauren outlet gucci outlet online coach outlet online cheap oakley sunglasses michael kors uk malone souliers moncler jackets cheap jordan shoes off-white clothing air jordan shoes polo ralph lauren shirts tory burch outlet online pandora charms sale clearance ralph lauren shirts tory burch outlet stores uggs outlet canada goose jackets outlet nike air huarache ugg outlet polo ralph lauren outlet michael kors outlet clearance ysl outlet online swarovski uk christian louboutin shoes suicoke sandals nike air max 90 adidas wings shoes coach factory outlet kate spade sale cheap soccer jerseys supreme t shirts michael kors canada coach outlet canada goose outlet store coach handbags outlet wellensteyn outlet canada goose outlet store longchamp handbags sale polo ralph lauren outlet red bottoms mbt christian louboutin shoes michael kors outlet ralph lauren polo mulberry bags michael kors outlet online ferragamo shoes air jordan shoes cheap jordan shoes cheap ray ban sunglasses cazal outlet michael kors outlet online kate spade handbags adidas shoes coach outlet store online louboutin shoes ugg boots on sale canada goose outlet store pandora charms sale clearance adidas store christian louboutin shoes coach outlet ferragamo outlet canada goose outlet store nike revolution air max 2015 los angeles lakers jerseys cheap oakley sunglasses nhl jerseys coach outlet tory burch outlet online mulberry handbags air jordan shoes christian louboutin outlet christian louboutin outlet moncler outlet online ugg outlet uggs outlet cheap jordan shoes michael kors outlet clearance michael?kors?outlet?online uggs outlet moncler outlet store north face outlet air force 1 shoes cheap ray ban sunglasses hermes birkin bag coach outlet online fred perry polo canada goose outlet store james harden shoes kate spade sale coach outlet online gucci bags fila sneakers michael kors outlet online adidas y3 shoes cheap ugg boots ed hardy outlet ugg outlet coach outlet michael kors outlet online ralph lauren outlet coach outlet online michael kors outlet lacoste shirts ugg boots clearance kate spade air jordan shoes ferragamo shoes nike shoes outlet coach outlet michael kors outlet online michael kors outlet online fitflops kate spade handbags michael kors outlet online michael kors outlet clearance ugg boots ugg outlet north face denail jacket clearance cheap jerseys wholesale oakley sunglasses wholesale oakley sunglasses wholesale mulberry outlet,mulberry handbags outlet fitflops tory burch handbags coach outlet online cheap jerseys wholesale cheap jordans yeezy boost uggs outlet pandora charms sale clearance herve leger dresses foamposite shoes ravens jerseys 49ers jersey canada goose jackets outlet canada goose outlet coach outlet online polo ralph lauren outlet jordan 3 jordan shoes uggs outlet michael kors outlet clearance michael kors factory outlet canada goose jackets manolo blahnik outlet moncler outlet online christian louboutin shoes birkenstock shoes adidas crazy mulberry handbags sale true religion outlet canada goose outlet online broncos jerseys cheap nba jerseys lebron shoes pandora charms sale clearance louboutin outlet burberry outlet store uggs outlet uggs outlet jordan 4 jordan shoes nike air force 1 kate spade handbags salomon outlet christian louboutin shoes swarovski outlet store nike uk store nobis jackets coach outlet burberry outlet online jordan retro cheap ray ban sunglasses fitflops sale clearance ugg boots clearance pandora outlet michael kors outlet clearance coach factory outlet michael kors handbags outlet air jordan retro christian louboutin shoes nike shoes outlet canada goose jackets true religion uk toms outlet uggs clearance hermes outlet store light up shoes christian louboutin shoes true religion jeans coach outlet online michael kors outlet online canada goose outlet pandora charms sale clearance longchamp pas cher michael kors outlet online mulberry handbags nike shoes outlet prada outlet online cheap nba jerseys uggs outlet christian louboutin shoes canada goose jackets new balance outlet coach outlet online canada goose outlet store cheap jordans kate spade sale michael kors outlet uggs outlet canada goose outlet store nfl jerseys mbt gucci outlet store undefeated shoes mcm backpacks texans jerseys canada goose outlet supreme clothing uk michael kors outlet online true religion outlet kobe bryants shoes christian louboutin shoes canada goose jackets uggs outlet cheap jordans free shipping true religion outlet ray ban sunglasses outlet canada goose jackets outlet tory burch outlet online air jordan shoes canada goose outlet store christian louboutin pas cher toms outlet coach factory store uggs outlet uggs outlet ray ban sunglasses outlet cheap jordans for sale air jordan shoes longchamp pliage longchamp pliage cheap ugg boots birkenstock shoes fitflops sale clearance marc jacobs sale canada goose outlet bottega veneta outlet online michael kors outlet online jordan shoes canada goose jackets pandora outlet coach outlet online coach outlet clearance chrome hearts online store christian louboutin shoes mishka snapbacks mulberry handbags adidas outlet online under armour outlet blackhawks jerseys pandora outlet moncler coats ralph lauren outlet coach outlet online true religion jeans pandora charms adidas nmd r1 coach factory outlet coach outlet canada goose jackets cheap nhl jerseys coach outlet online moncler outlet online pandora charms michael kors outlet online hermes belts pandora jewelry polo ralph lauren christian louboutin shoes mbt outlet cartier bracelet san antonio spurs tory burch outlet online louboutin shoes fitflops shoes vans sneakers nike factory store jimmy choo shoes coach factory outlet fitflops ralph lauren outlet ray ban sunglasses mulberry uk cheap basketball shoes cheap ray ban sunglasses true religion outlet coach factory outlet ugg outlet cheap oakley sunglasses coach handbags on sale 2018 world cup jerseys michael kors canada goose canada goose jackets givenchy handbags golden state warriors off white clothing cleveland cavaliers jerseys true religion outlet coach outlet longchamp outlet pandora jewelry camisetas futbol baratas cheap jordan shoes ugg boots clearance longchamp bags ugg outlet coach outlet canada goose outlet store kate spade sale christian louboutin shoes ugg boots tory burch outlet online cheap ray ban sunglasses longchamp handbags polo ralph lauren outlet michael kors outlet online nike shoes outlet fitflops sale clearance ray ban sunglasses outlet true religion outlet coach canada ugg outlet supra shoes sale lacoste polo cheap jordans canada goose outlet store ralph lauren outlet nike blazer pas cher michael kors uk adidas yeezy boost kate spade sale fitflops sale clearance pandora outlet kate spade handbags new york knicks links of london jewellery pandora charms sale clearance michael kors outlet clearance yeezy boost 350 nike air max 2017 michael kors handbags tory burch outlet online ferragamo shoes sale ralph lauren outlet pandora charms sale clearance ecco outlet gucci outlet online christian louboutin shoes ralph lauren femme coach outlet online north face outlet true religion outlet store kate spade outlet online polo outlet online snapbacks wholesale miu miu shoes prada shoes for men moncler outlet store toms outlet canada goose outlet store christian louboutin shoes true religion outlet ferragamo shoes ralph lauren polo canada goose jackets outlet adidas outlet online canada goose jackets nike air max 97 colts jerseys canada goose jackets pandora charms sale clearance cheap nba jerseys jordan shoes michael kors outlet online oakley sunglasses wholesale jordan retro canada goose jackets michael kors outlet clearance ugg boots gucci outlet online true religion outlet mbt coach outlet online mont blanc pens nike air max 90 coach outlet store cheap jerseys wholesale mulberry bags uggs outlet valentino shoes michael kors outlet online 20181004

daisyjane2018
Posted On: 11/9/2018 1:28:06 AM

The league announced the news this morning, writing in a press release that,cheap authentic jerseys "Beginning Friday, November 9, NFL team 'outfits' will be available in the cheap nfl jerseys Shop. This unique opportunity will give Fortnite players the ability to purchase and customize up to eight outfits representing their favorite NFL teams."cheap jerseysWe're just getting started, though! There will also be "football-themed emotes, harvesting tools, gliders, and even a referee outfit." cheap sports jerseys Even a referee outfit! cheap jerseys from chinaSo there you have it, Fortniters (Fortnitees?). Your prayers have been answered. Everyone gets their favorite team's football jersey,wholesale jerseys and themed emotes, and harvesting tools, and gliders. Click here to choose the new cheap authentic jerseys from china and wholesale nfl jerseys! Receive comprehensive coverage of the Bears and stream the ‘Football Aftershow’ easily on your device.click here cheap authentic nfl jerseys.It's not a giant surprise,custom cowboys jersey but it's still impressive to see. Fortnite is hugely popular among professional athletes, and it's football season,discount jerseys after all. Epic Games just announced an official partnership with the NFL to bring licensed jerseys to the popular battle royale game, letting players don the jerseys of their favorite teams as they blast each other into oblivion.discount nfl jerseys cheap nfl jerseys cheap jerseys cheap jerseys from china wholesale jerseys cheap nfl jerseys from china china jerseys nfl jerseys china wholesale nfl jerseys cheap authentic nfl jerseys cheap jerseys online cheap authentic jerseys cheap sports jerseys cheap wholesale jerseys china wholesale jerseys discount nfl jerseys cheap authentic jerseys from china discount jerseys custom cowboys jersey Click here GOOGLE FACKBOOK Amazon nfl jerseys cheap cheap college football jerseys cheap nfl jerseys china cheap football jerseys custom jerseys cheap cheap nfl gear cheap nfl authentic jerseys cheap jerseys nfl nfl football jerseys cheap cheap nfl football jerseys cheap nfl jerseys free shipping cheap nfl nike jerseys custom nfl jerseys cheap nfl cheap jerseys