Adding users in Sitecore with specific roles using Powershell

we can use Sitecore Powershell to create users in Sitecore. This is how we can create a single user in sitecore.

$username=”contentbuser”
$userpwd=”content@123″
$roles=”Author,Developer”
$email=”test@test.com”

Write-host “Creating User: $($username)”
New-User -Identity $($username) -Enabled -Password $($userpwd) -Email $($email) -FullName “$($username)”

Lets add some roles to it.

$($roles).Split(“,”) | ForEach {
Write-host “Adding user to role: $_ “
Add-RoleMember -Identity $_ -Members “$($username)”
}

If you you want to make it as an administrator

Set-User $($username) -IsAdministrator $true

Here you can assign multiple roles to it too.

Create Bulk users in Sitecore

Now Imagine a scenario where you have to create number of users where you have a csv file with the necessary information mentioned above like username, password, email and roles to be assigned. you can use below script to automate creating number of users

Upload a csv file from your local to sitecore upload folder. This is very important to note because you might get permission issue error if you want to write at some other location. This will be helpful.

$dataFolder = [Sitecore.Configuration.Settings]::DataFolder
$tempFolder = $dataFolder + “\temp\upload”
$filePath = Receive-File -Path $tempFolder -overwrite

if($filePath -eq “cancel”){
exit
}

$Usersdata = Import-Csv -Path $filePath

foreach($user in $Usersdata) {
    Write-Verbose "Creating User: $($user.Username)"
   New-User -Identity $($user.Username) -Enabled -Password $($user.Password) -Email $($user.Email) -FullName "$($user.Name)"
    
    #Set-User $($user.Username) -IsAdministrator $true
    
   $($user.Roles).Split(",")  | ForEach {
     Write-Verbose "Adding user to role: $_ "
     Add-RoleMember -Identity $_ -Members "$($user.Username)"
   }
}

here Username, Password, Email and Roles are csv fields.