Power Shell Script to Create Users in SharePoint Dev Environment

Ashok Raja
 
Solutions Architect
June 20, 2012
 
Rate this article
 
Views
440

While switching between different VMs, I used to spend most of the time in setting up the pre-requisites of the Application on which I am working on. Out of those pre-requisites one would be creation of user accounts. Most of the applications demand different set of users across different SharePoint User Groups, especially while working with MySites. Creating multiple users is tedious and time consuming activity. So I have automated this process with the help of PowerShell to save a bit of time.

Now lets see how we can create Active Directory user accounts through PowerShell scripts. This script does not have any dependency on any third party snap ins and it can work on any Windows 2008 R2 server configured with Active Directory.

In this script , I am loading a set of user details from a CSV file and creating those user user accounts in Active Directory. During this process the script validates the existence of those users and skips the users if they are already present.

Sample CSV file

LogIn,FirstName,LastName,Email,Password,PasswordNeverExpires
u1,Share Point,User 1,u1@dev.in,P@ssw0rd,true
u2,Share Point,User 2,u2@dev.in,P@ssw0rd,true
u3,Share Point,User 3,u3@dev.in,P@ssw0rd,true

More on Script

The script contains an overloaded function named as  Get-Principal . The one with parameters can be used to create user accounts under the context of a specific user.  The one without parameter executes under the context of logged in user.

CreateUsersFromCsv is the function that has to be called to execute the script . It accepts file path as Parameter.  As a second parameter a Boolean value has to be passed to switch user context.

 #Script to create user accounts by Ashok Raja . T
 #Provide valid Parameters for below varaibles if the script has to be executed in a specific user account
 
 
 $AdDomain="" # Provide Domain Name . Example =>  $AdDomain="GlobalCorp" 
 $AdUser="" # Provide name of Active directory administrator  . Example =>  $AdUser="Administrator" 
 $AdUserPwd="" # Provide Administrator Password . Example =>  $AdUserPwd="myPass" 
 
 
 function CreateUsersFromCsv([String]$FullPathOfCsvFile,[bool] $UseLoggedInUsersCredentials )
 {
 
 	# BEGIN - Internal Functions
 
 	function Get-ContextPrincipal()
 	{
 		Add-Type -AssemblyName System.DirectoryServices.AccountManagement
 		$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
 		$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ct)
 		return $pc
 	}
 
 	function Get-Principal([String]$uName, [String]$uPwd,[String]$ctxDomain)
 	{
 		Add-Type -AssemblyName System.DirectoryServices.AccountManagement
 		$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
 		$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($ct,$ctxDomain,$uName,$uPwd)
 		return $pc
 	}
 
 	function IsUserExists([System.DirectoryServices.AccountManagement.PrincipalContext] $ctx,[String] $uName)
 	{
 		$curUser= [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ctx, $uName)
 		return $curUser -ne $null
 	}
 	function IsNullOrEmpty($str) {if ($str) { return $false} else {return $true}}
 	function CreateUsers([String]$FullFilePath,[bool] $UseLocalAccount )
 	{
 		if([IO.File]::Exists($FullFilePath) -eq $true)
 		{		
 			if($UseLocalAccount)
 			{
 				$CurrentContext=Get-ContextPrincipal
 			}
 			else
 			{
 				[bool] $DataValid =$true;
 				if(IsNullOrEmpty($AdDomain))
 				{
 					Write-Host  Domain Name cannot be null !!!
 					$DataValid =$false;
 				}
 				if(IsNullOrEmpty($AdUser))
 				{
 					Write-Host  AD Admin Name cannot be null !!!
 					$DataValid =$false;
 				}
 				
 				if(IsNullOrEmpty($AdUser))
 				{
 					Write-Host  Password cannot be null !!!
 					$DataValid =$false;
 				}
 				if($DataValid)
 				{
 					$CurrentContext=Get-Principal -uName $AdUser -uPwd $AdUserPwd -ctxDomain $AdDomain
 				}
 				else
 				{
 					Write-Host  Modify the values in Power shell script file or  assign  UseLoggedInUsersCredentials  to true to use credentials of loggedin user.	
 					return;
 				}
 			}
 		 
 			Import-Csv $FullFilePath | ForEach-Object { 
 				#$tempUser=IsUserExists -ctx $CurrentContext -uName $_.LogIn
 				if(IsUserExists -ctx $CurrentContext -uName $_.LogIn)
 				{
 					Write-Host User  $_.LogIn already exist !!!
 				}
 				else
 				{
 					$newUser= New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal($CurrentContext, $_.LogIn,$_.Password,$_.PasswordNeverExpires)
 					$newUser.UserPrincipalName = $_.LogIn
 					$newUser.GivenName = $_.FirstName
 					$newUser.DisplayName = $_.FirstName + " " + $_.LastName
 					$newUser.Name = $_.FirstName + " " + $_.LastName
 					$newUser.EmailAddress =$_.Email
 					$newUser.Surname =  $_.LastName
 					$newUser.PasswordNeverExpires = $_.PasswordNeverExpires
 					$newUser.Save()
 					Write-Host User  $_.LogIn Created
 				}
 			}
 				Write-Host Done !!!!
 		}
 		else
 		{
 		Write-Host  Invalid File Path !!!
 		Write-Host  Please provide a valid file name ...
 		Write-Host  Example
 		Write-Host  CreateUsersFromCsv -FullPathOfCsvFile "C:/User/users.csv" -UseLoggedInUsersCredentials $true 	
 		Write-Host  Example - with different crentials " Change the values for paramenters in the top of the file and change -UseLoggedInUsersCredentials to $false."
 		Write-Host  CreateUsersFromCsv -FullPathOfCsvFile "C:/User/users.csv" -UseLoggedInUsersCredentials $false  	
 		}
 	}
 	# END - Internal Functions
 
 	# BEGIN - Invoke Functions
 	CreateUsers -FullFilePath $FullPathOfCsvFile -UseLocalAccount $UseLoggedInUsersCredentials
 
 	# END - Invoke Functions
 
 
 }
 	write-Host
  	Write-Host  --------------------------------------- How to Execute --------------------------------------
 	Write-Host  CreateUsersFromCsv to create users
 	Write-Host  Example - with logedin user credentials
 	Write-Host  CreateUsersFromCsv -FullPathOfCsvFile "C:/User/users.csv" -UseLoggedInUsersCredentials $true 	
 	Write-Host  Example - with different crentials " Change the values for paramenters in the top of the file and change -UseLoggedInUsersCredentials to $false."
 	Write-Host  CreateUsersFromCsv -FullPathOfCsvFile "C:/User/users.csv" -UseLoggedInUsersCredentials $false 
 	Write-Host  ---------------------------------------------------------------------------------------------
 	write-Host

The below is the screen shot of my PS window

CreateUsersInPowerShell

Download
Download Source

Author Info

Ashok Raja
 
Solutions Architect
 
Rate this article
 
I am Ashok Raja, Share Point Consultant and Architect based out of Chennai, India. ...read more
 

Leave a comment