-1

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();
sp9
  • 755
  • 3
  • 11
  • 22

1 Answers1

0

Unless you have a large input file I'd split the file multiple ways:

  1. at 3 consecutive line breaks to separate the groups from each other,
  2. at 2 consecutive line breaks to separate the user list from the group name,
  3. at commas to get the list of user names.

Something like this should do:

(Get-Content 'C:\temp\test.txt' -Raw) -split "`r`n`r`n`r`n" | ? { $_ } | % {
  $group, $userlist = $_ -split "`r`n`r`n"
  $users = $userlist -split ','

  # do stuff with $group and $users
}

Note that the parameter -Raw requires PowerShell v3 or newer. With older versions use -join before -split:

(Get-Content 'C:\temp\test.txt') -join "`r`n" -split "`r`n`r`n`r`n" | ...
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Thanks for the reply Ansgar but this is not working correctly. I ll update my question with the new format I have like u suggested but it's not working correctly. The $group name is showing all User values and $User is empty – sp9 Jun 03 '15 at 11:51
  • @sp9 If you have 3 line breaks between groups and 2 line breaks between group and userlist you need to adjust the splitting patterns accordingly, of course. See updated answer. BTW, this would be a lot simpler if you chose an easier to handle format, for instance `group1:user1,user2,user3...` – Ansgar Wiechers Jun 03 '15 at 13:21