Add multiple users, groups and groups permission from *.csv to SharePoint 2013 using powershell

The goal is to add more than 600 users and add them to 82 groups with special departments aliases. This is some kind of pseudocode which referenece to *.csv file which contains two columns of data like “user” login and “group” name.

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Write-Host "Connect Sharepoint Cmd-Let" 
Add-PSSnapin Microsoft.SharePoint.PowerShell 
}

$Site = Get-SPSite https://mysharepoint
$Web = $Site.RootWeb

$ownerName = "DOMAIN\SpAdmin"
$op = New-SPClaimsPrincipal CLUSTER\SpSetupUsr -IdentityType WindowsSamAccountName
$owner = $Web | Get-SPUser $op

$csvlocation = "c:\csv\users.csv"
$values = Import-Csv $($csvlocation) -Delimiter ";" 

$values | ForEach-Object {

#Checking this group already exist in SP   
if(!$Web.SiteGroups[$_.group] -eq $_.group) {

    #Adding Group and Set Permission
    $Web.SiteGroups.Add($_.group, $owner, $null, $null) 
    $SPGroup = $Web.SiteGroups[$_.group]
    $assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($Web.SiteGroups[$_.group])
    $role = $web.RoleDefinitions["Read"]
    $assignment.RoleDefinitionBindings.Add($role);
    $web.RoleAssignments.Add($assignment)
}

#Adding User to Group
$SPGroup = $Web.SiteGroups[$_.group]
$SPGroup.AddUser($_.user,"","",$_.group) 

#Added User and Group listed on console 
Write-Host "User :" $_.user "added to Group " $_.group

}

$web.Dispose()
$site.Dispose()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s