Populating Active Directory with Users and Groups with PowerShell

I whipped up this script in order to populate my Lab VM running Windows Server 2008 R2 with users and groups. Plus I was bored and wanted to work on my PowerShell 🙂

I did have to load an update so that I could run a few of the cmdlets(New-ADUser, New-ADGroup, & Add-ADGroupMember) you can find the update and info on it here http://support.microsoft.com/kb/2806748

#### Create Users and Groups in Fresh AD ####
#### I use this script to populate users and groups on a test server ####
#### Load Active Directory Module ####
Import-Module ActiveDirectory

#### CSV Format Below ####
## FirstName,LastName,UserName,Password,EmailAddress,Group1,Group2,Group3,Group4,Group5,Group6,Group7,Group8,Group9,Group10,Group11,Group12
## A. Scott,Wright,ascott0,WrA.57co,ascott0@adventure-works.com,DesktopAdmins,,Production Control,,,,,,,,,



### Import our CSV File ###


$UserList = Import-Csv "C:\ADShare\Powershell\AddUsers.csv"

$EmployeeOU = "OU=Employees,DC=lmnop,DC=local"


foreach ($User in $UserList){
	$FullName = $User.FirstName + " " + $User.LastName
	$Password = $User.Password
	$SAM = $User.UserName
	
	##Build Group List##
	$GroupList = @( 
	 $User.Group1
	,$User.Group2
	,$User.Group3
	,$User.Group4
	,$User.Group5
	,$User.Group6
	,$User.Group7
	,$User.Group8
	,$User.Group9
	,$User.Group10
	,$User.Group11
	,$User.Group12)
	
	
	##Create User##
	New-ADUser -Name "$FullName" -SamAccountName $SAM -UserPrincipalName $SAM -DisplayName "$FullName" -GivenName $User.FirstName -Surname $User.LastName -EmailAddress $User.EmailAddress -AccountPassword ( ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$EmployeeOU" -PasswordNeverExpires $true
	
	
	
	##Check if group exists and Create if needed##
	Foreach($ADGroup in $GroupList){
		#Skip blanks
		if($ADGroup -ne ""){
				if(Get-ADGroup -Filter{SamAccountName -eq $ADGroup}){
				#Write-Host $ADGroup ": Exists"
				#Add User to Group
				Add-ADGroupMember $ADGroup $SAM
				Write-Host "Added $SAM to $ADGroup"
				}else{
					#Write-Host $ADGroup ":Does Not Exist"
					#Create Group, Then add user to Group
					New-ADGroup -Name "$ADGroup" -Path "$EmployeeOU" -GroupScope Global
					Add-ADGroupMember $ADGroup $SAM
					Write-Host "Created Group $ADGroup"
					
				}
		}
	}
	

}

Here is the complete CSV file I used (basically from the AdventureWorks Sample DB) AddUsers.csv

PowerShell is always fun.

Leave a Reply