Thursday, May 1, 2014

Adding a user to a SharePoint Group using PowerShell

 

This seems to be a common and repetitive task considering that it probably needs to be done quite often.

Therefore, it makes sense to try and automate this process as much as possible using Windows PowerShell.

You may find a lot of sample scripts out on the web and I have tried many of them, but quite a few of them DO NOT WORK!

Therefore, I am providing you with a PowerShell script that actually DOES work.  You can manipulate and modify the script as needed to achieve your goals.

Without further ado, here is the PowerShell script:

$url = "http://sp2013/sites/mysitecoll"
$userName = "spfarm\sp2013_svc"
$site = new-object Microsoft.SharePoint.SPSite($url) 
$web = $site.OpenWeb() 
$siteGroups = $web.SiteGroups;
 
Clear-Host
 
$mySiteGroups = @(); 
foreach($group in $groups) 
{ 
    Write-Host $group
    $mySiteGroups += $group;
}#foreach
 
 
 
$members = $mySiteGroups[0]
$owners = $mySiteGroups[1]
$visitors = $mySiteGroups[2]
 
#Convert the user name to an SPUser account
$spUser = $web.Site.RootWeb.EnsureUser($userName);
#Add the user to the specified SharePoint Group
$owners.AddUser($spUser);
$web.Update();
$web.Dispose();
 
 
Write-Host "User " $userName   "added to " $owners

No comments:

Post a Comment