SharePoint 2010: Add a User in a SharePoint Site using PowerShell
This topic is a how to. Please keep it as clear and simple as possible. Avoid speculative discussions as well as a deep dive into underlying mechanisms or related technologies. |
What is Windows Powershell ?
Windows PowerShell command-line interface is a new command-line tool and supporting scripting language from Microsoft that complements Cmd.exe in the Windows administration context. In the SharePoint administration context, Windows PowerShell supersedes the Stsadm.exe administration tool. Moving forward, you should use Windows PowerShell scripting technology to develop any new command-line scripts in SharePoint Foundation 2010.
Firstly we need to load the SharePoint Snap-in to allow the session to use the SharePoint objects. Note that you don't need to do this if you're using the SharePoint 2013 Management Shell as it already has the Snap-in loaded.
Add-PSSnapin "Microsoft.Sharepoint.PowerShell"
Get the SPWeb object for the site we want to add the users to.
$web = Get-SPWeb "http://mossportal"
There's two aspects to adding a user to a site. First you add the user themselves and the easiest way to do that is by using the SPWeb.EnsureUser() method detailed: here
$userObject = $web.EnsureUser("Contoso\AlexBrassington")
There are two ways to add users to a site, individually or to a group. Groups are the preference as they are far easier to manage in the long run.
Let's get the group object to add our SPUser object to.
$group = $web.SiteGroups["Site Members"]
Finally let's add the user to the group
$group.AddUser($userObject)
And it's done. The user has now been added to the site in the appropriate group.
See Also
- What's New: Windows PowerShell for SharePoint
- PowerShell Portal
- Wiki: Portal of TechNet Wiki Portals
Other Languages
This articles is also available in the following languages:
Italian (it-IT)
French (fr-FR)