Monday, May 5, 2014

Removing a user from a SharePoint Group using PowerShell

 

If you read my earlier post about Adding a User to a SharePoint Group using PowerShell (http://samirvaidya.blogspot.com/2014/05/adding-user-to-sharepoint-group-using.html), you are probably also interested in Removing a User from a SharePoint Group using PowerShell:

$url = "https://sharepointdev.spfarm.spcorp.com/sites/mysitecoll"
$userName = "spfarm\sp2013_svc"
$site = New-Object Microsoft.SharePoint.SPSite($url) 
$web = $site.OpenWeb() 
$siteGroups = $web.Groups;
 
Clear-Host
 
$mySiteGroups = @(); 
foreach($group in $siteGroups) 
{ 
    Write-Host $group
    $mySiteGroups += $group;
}#foreach
 
 
 
$members = $web.Groups[$mySiteGroups[0]];
$owners = $web.Groups[$mySiteGroups[1]];
$visitors = $web.Groups[$mySiteGroups[2]];
 
#Convert the user name to an SPUser account
$spUser = $web.Site.RootWeb.EnsureUser($userName);
Write-Host $spUser.ID
 
$owners.RemoveUser($spUser)
 
#This method also works but prompts the user to verify that the user should be removed
#Remove-SPUser -Identity $spUser -Web $url -Group $owners
 
$web.Update();
$web.Dispose();
 
 
Write-Host "User " $userName   "removed from " $owners

No comments:

Post a Comment