Advertisement
private775

SharePoint: populate security groups from CSV

Apr 27th, 2015
422
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #Group,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10
  2. #Initiators,John Doe,Nicholas Smith,Jonathan Smith,,,,,,,
  3. #Reviewers,Nicholas Smith,Jonathan Smith,Dave Smith,Tosha Doe,,,,,,
  4.  
  5. # Read CSV and populate groups
  6.  
  7. $webUrl = "http://acme.com/sites/acme/PremiumPayment2"
  8. $csvPath = "C:\Temp\20150427\UserGroupSetup.csv"
  9.  
  10. $csv = Import-Csv -Path $csvPath
  11.  
  12. $w = get-spweb $webUrl
  13.  
  14. function EmptyGroup($g){
  15.     "Cleaning group: $($g.Name)"
  16.     while($g.Users.Count -gt 0){
  17.         $u = $g.Users[0]
  18.         "Removing user: $($u.DisplayName)"
  19.         $g.RemoveUser($u)
  20.     }
  21. }
  22.  
  23. foreach($gg in $csv){
  24.     $gName = $gg.Group
  25.     "Checikng if exists: `"$($gName)`""
  26.     $g = $w.SiteGroups[$gName]
  27.     if($g -eq $null){
  28.         throw "Group `"$($gName)`" not found"
  29.     }
  30. }
  31.  
  32. $uniqueNames = new-object -TypeName "System.Collections.Generic.List[string]"
  33. foreach($gg in $csv){
  34.     $gName = $gg.Group
  35.     for($i = 1; $i -le 10; $i++){
  36.         $name = $gg."P$($i)"
  37.         if($name -ne $null -and $name -ne ""){
  38.             if(-not $uniqueNames.Contains($name)){
  39.                 $uniqueNames.Add($name)
  40.             }
  41.         }
  42.     }
  43. }
  44.  
  45. $allUsers = get-spuser -Web $w.Url
  46. $userDic = new-object -TypeName "System.Collections.Generic.Dictionary[string,Microsoft.SharePoint.SPUser]"
  47.  
  48. "Checikng users"
  49.  
  50. foreach($name in $uniqueNames){
  51.     $user = $allUsers |?{$_.DisplayName -eq $name }
  52.     if($user -eq $null){
  53.         throw "User not found: $($name)"
  54.     } else {
  55.         if($($user.GetType().Name) -eq "SPUser"){
  56.             $userDic.Add($name, $user)
  57.         } else {
  58.             $acmeUser = $user|?{$_.UserLogin.StartsWith("ACME\")}
  59.             $userDic.Add($name, $acmeUser)
  60.         }
  61.     }
  62. }
  63.  
  64. foreach($gg in $csv){
  65.     $gName = $gg.Group
  66.     "Processing group: `"$($gName)`""
  67.     $g = $w.SiteGroups[$gName]
  68.     EmptyGroup $g
  69.     for($i = 1; $i -le 10; $i++){
  70.         $name = $gg."P$($i)"
  71.         if($name -ne $null -and $name -ne ""){
  72.             $user = $userDic[$name]
  73.             $g.AddUser($user)
  74.         }
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement