I am trying to add new groups and add users to the groups in SharePoint using PowerShell. So far I have this script which does the task. I want to modify the script so it can read from a text file which has the groups and the users in this format (or recommend another way of doing it).
Group1
User1,User2,User3 etc.
Group2
User5,User7 etc.
Can someone please tell me how I can achieve this task?
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
$SiteUrl = "http://www.dev.com"
$Web = Get-SPWeb $SiteUrl
$description = "Group with contribute access."
$permissionLevel = "Contribute"
$groups = "1", "2"
foreach($groupName in $groups)
{
$web.SiteGroups.Add($groupName, $web.SiteUsers["Test\data"], $web.SiteUsers["Test\data"], $description)
$group = $web.SiteGroups[$groupName]
$loc = Get-Location
$Users = "Test\data"
$roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)
$roleDefinition = $web.Site.RootWeb.RoleDefinitions[$permissionLevel]
$roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
$web.RoleAssignments.Add($roleAssignment)
$web.Update()
foreach ($User in $Users) {
$Web.EnsureUser($User)
Set-SPUser -Identity $User -Web $SiteUrl -Group $group
}
}
$Web.Dispose();