Search This Blog

Wednesday, 22 April 2015

Powershell - Adding users to SPGroups

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Write-Host "Connect Sharepoint cmd-Let"
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}
$url = Read-Host "Enter site URL (Eg: http://<HostName>:1111/sites/sitecollname )"
$site = new-object Microsoft.SharePoint.SPSite($url)
$web = $site.OpenWeb()
$groups = $web.sitegroups

$userName = Read-Host "Enter username"
write-host "--------------"
$i = 0;
$myGroups = @();
foreach($group in $groups) {
  if($group -match "admin") {
        $myGroups += $group
    }
}

foreach ($gr in $myGroups) {
    write-host $gr
#add user to SP Group
    Set-SPUser -Identity $userName -web $url -Group $gr
    $theGroup = $web.SiteGroups[$gr]    
    $theUser = $web.AllUsers.Item($userName)

#Remove user from SP Group
#   $theGroup.RemoveUser($theUser);
    write-host "User " $userName   "added to " $gr
}

No comments:

Post a Comment