For this PowerShell script I have created a function called AddGroupToSite, allowing you to assign a SharePoint group (must already be created in the site collection) to a site along with a permission level by specifying one line of script. This first section sets up the SPWeb object and the function:
$web = Get-SPWeb "http://portal"
function AddGroupToSite ($web, $groupName, $permLevel)
$account = $web.SiteGroups[$groupName]
$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
$role = $web.RoleDefinitions[$permLevel]
Functions are very useful in PowerShell because they allow you to reduce the number of lines in your script by calling the same routine multiple times, passing in various parameters of your choosing to vary the properties of the function – in the example above, I am passing in the SPWeb object, group name and permission level. You can find more information on using functions by typing get-help about_Functions from PowerShell itself or there are plenty of tutorials on the subject around the Web or in books. Once we have our function set up, we can call it and pass the relevant parameters as follows:
AddGroupToSite -web $web -groupName "Site Admins" -permLevel "Full Control"
AddGroupToSite -web $web -groupName "Site Readers" -permLevel "Read"
These lines add two SharePoint groups – Site Admins and Site Readers – to the site http://portal and assign them Full Control and Read permissions respectively. You could also feed values from a CSV or XML file into your function to automate this for a number of sites as a bulk operation. If you need to break permission inheritance on the site before adding the groups, add one of the following lines just after the $web = Get-SPWeb http://portal line at the top of the script:
#Break permissions inheritance and copy the groups from parent site into this site
#Break permissions inheritance and assign the current user as the only member of this site
UPDATE - 17th February 2011: I have written an article expanding on the subject of this post describing how to use PowerShell to assign SharePoint and AD group/user permissions for all sites in a site collection. Please click here for details.