Monday, 12 July 2010

Adding SharePoint groups with permission levels to sites using PowerShell

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]
    $assignment.RoleDefinitionBindings.Add($role);
    $web.RoleAssignments.Add($assignment)
}

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
$web.BreakRoleInheritance($true)

#Break permissions inheritance and assign the current user as the only member of this site
$web.BreakRoleInheritance($false)

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.

61 comments:

  1. Is there a way to assign the permission of the group throughout the site collection? I would like a specific group read access throughout the site collection for all content. note: some sites have unique permission settings. Thanks for your feedback on this.

    ReplyDelete
  2. This can be done and I hope to get something together for a new blog post soon.

    ReplyDelete
  3. Wonderful, I look forward to seeing it. I have limitted programing skills, but do plan to study up on PowerShell. As a Sharepoint admin I can see this would be a very usefull skill to have.

    ReplyDelete
  4. Is there a way to change the default member group to another sharepoint group using Powershell?

    ReplyDelete
  5. Hi, you could try this:

    $web = Get-SPWeb http://portal

    #Find ID for the group you wish to assign as member
    $web.Groups["GROUP NAME"].ID

    #Set it to be the new member group for the site
    $web.Properties["vti_associatemembergroup"] = "INSERT ID HERE"
    $web.Update()
    $web.Dispose()

    ReplyDelete
  6. Hi Phil,
    Discovered this blog today, very useful stuff!
    I'm trying to add a AD group to SP group (without iterating over the users inside, just the whole group in one go).
    Do you think this is possible? Any pointers?
    Thanks,
    Laurence

    ReplyDelete
  7. This is one of the best articles so far I have read online. No crap, just useful information. Very well presented. Its really helpful for beginner as well developer. This link also helpful, check out it..

    http://mindstick.com/Articles/06e20e89-d95f-45a2-b3cd-7fd011ed8738/?Getting%20the%20permission%20levels%20from%20SharePoint%202010%20using%20C#

    Its also help me lot in complete my task.

    Thanks

    ReplyDelete
  8. If you're going to use BreakRoleInheritance, check out this article http://ilyal-technology.posterous.com/naaasty-sharepoint-2010-bug.

    ReplyDelete
  9. Is it possible at all to modify this so that you can remove a specified permission level from a group? I stuck it in a script with a foreach to add a group with permissions to a bunch of subsites. What I really need is something that can look for groups with "contribute" permission then remove that and add "Read" permissions. Possible?

    ReplyDelete
  10. Hi...thanks sharing us the code...but it did not work for me...i got error "new object : constructor not found"...Please help me on this...

    ReplyDelete
  11. This just saved me a couple of hours ;) Much thanks!

    ReplyDelete
  12. Any way to modify this to add a user and copy the $role from another user? I have the below, but not working.. getting an error on line: $role = $web.RoleDefinitions.[$newRoleDef]

    foreach($Web in $Site.AllWebs)
    {

    if($Web.HasUniqueRoleAssignments -eq $True)
    {
    foreach($WebRoleAssignment in $Web.RoleAssignments )
    {
    if($WebRoleAssignment.Member.userlogin)
    {
    if($WebRoleAssignment.Member.LoginName -eq $SearchUser)

    $WebUserPermissions=@()
    foreach ($RoleDefinition in $WebRoleAssignment.RoleDefinitionBindings)
    {

    $newRoleDef = $RoleDefinition.Name
    $assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
    $role = $web.RoleDefinitions.[$newRoleDef]
    $assignment.RoleDefinitionBindings.Add($role)
    $_.RoleAssignments.Add($assignment)

    ReplyDelete
  13. can you please help on this phil
    I need to Add one user with Read permission to the all site colllection in the webapplication.

    i saw your Article http://get-spscripts.com/2011/02/add-sharepoint-or-ad-groupuser-to-all.html using this Article i adding user only one site collection but i need to add allsite collection in the webapplication .

    Please help on this Phil.

    Thanks ,
    KVReddy.

    ReplyDelete
  14. Installation procedure will splashthat.com/ certainly use up to couple of mins Official Website and conserves its symbol in menu. Mobdro Download Select the Mobdro App from Android menu Mobdro APK as well as start downloading and streaming mobdro the videos on Windows XP.

    ReplyDelete
  15. For some reason I get errors with this :

    New-Object : A constructor was not found. Cannot find an appropriate constructor for type
    Microsoft.SharePoint.SPRoleAssignment.

    ReplyDelete
  16. Creehack allows limitless access blogspot.in/ to all the in-app purchases.It could bypass Get Info the payments for a large CreeHack Free Download for Android Smartphone APK App number of gaming and also entertainment CreeHack APK apps.Creehack does not require CreeHack Freedom support to work efficiently.

    ReplyDelete
  17. I don't apperceive what it is about the bendable blow and matte finish, but I accept a anemic atom for printed suede Christisn Louboutin Outlet. One of the best brands to cull this off is YSL Wallet Outlet. I accept to acquaint you about a backpack attraction of mine. I am in fact mad at myself that I did not splurge on the Ralph Lauren Polo Outlet Croc Muse Two which has two colors that I admire with a sueced croc pattern. To see a formed suede accomplishment off a Red Bottoms Outlet that I already adore, my affection melts. Replica Watches are additionally pretty reflective of their user's persona. Amazing furthermore multi-colored Replica Watches are commonly worn because of the younger. Conversely, exquisite dress Swiss Rolex Replica are regularly sported by highly developed gentlemen. And then usually there's the luxurious Swiss Replica Watches worn by the individuals who're properly to complete. Check out observing your mates furthermore you can before long see how the layouts are actually ranging.

    ReplyDelete
  18. También puede visitar una tienda de ladrillo y mortero de Michael Kors o su sitio web y comprar directamente un bolso Michael Kors desde allí. Usar un bolso de Michael Kors les permite a los demás reconocer que el habitante urbano educado toma la moda realmente con seriedad. Los bolsos de hombro son particularmente refinados y elegantes.

    {Bolsas Michael Kors Precios | Bolsos Michael Kors Outlet | Michael Kors Rebajas}

    En vacker konstnärlig skapelse av vävt läder, som ger ett skalskaligt utseende - liknar en snakeskin eller fiskhud, linjer utsidan av påsen. Läderens bältros är små läderringar. Det finns också gyllene accenter på väskan. Slutresultatet är svagt liknar kedjepost.

    {Michael Kors Rea | Michael Kors Väska Rea | Michael Kors Plånbok}

    ReplyDelete
  19. Nice thoughts with great helping content. I have also been seeking such thoughfull content to learn and appy in the life. We have also created such type of content on our site. You can refer out site for more ideas.
    Happy New Year 2019 Wishes Messages Sms in Bengali
    Merry Christmas 2018 SMS, Wishes, Messages, Greetings in Bengali
    Merry Christmas 2018 Wishes Messages in Marathi,funny christmas text sms

    ReplyDelete
  20. nice thoughts with great helping content. I have also been seeking such thoughfull content to learn and appy in the life. We have also created such type of content on our site.

    pip camera new version 2019

    ReplyDelete
  21. The article is very useful. Thanks for sharing. Also read our article about health and treatment information, I'm sure useful :)

    Pengobatan Penyakit Kanker Testis
    Obat Radang Tenggorokan di Apotik

    ReplyDelete
  22. The article is very useful. Thanks for sharing.

    Sketch Maker new version 2019

    ReplyDelete
  23. I was impressed, I have to say. In fact, I rarely Encounter educational and funny blogs. You may strike a nail on your head. Your idea is wonderful. The problem is one of which is not speaking intellectually. I am pleased that I am looking for one thing.

    ReplyDelete
  24. This article is actually a nice one it helps new internet viewers, who are wishing in favor of blogging. And Another one from the same article as Click Here for more news

    ReplyDelete
  25. This article is actually a nice one it helps new internet viewers, who are wishing in favor of blogging. And Another one from the same article as Click Here for more news

    ReplyDelete
  26. Hi there, You’ve done an incredible job. I will definitely digg it and personally recommend to my friends. I’m sure they will be benefited from this web site.

    Happy Valentines Day Images 2019
    Happy Valentines Day Clipart And Sayings
    Happy Valentines Day Poems And Pictures
    Happy Valentines Day Messages And Images
    Short Valentines Day Sayings And Poems

    ReplyDelete
  27. Thanks for sharing nice information with us. i like your post and all you share with us is uptodate and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. I found your blog using msn. This is an extremely well written article as click here . I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I’ll certainly comeback.

    ReplyDelete
  28. I am happy to be here and this wonderful article. I have found here lots of interesting information for my knowledge I need. all the details you provide to us, it was very helpful and useful, thanks for sharing this amazing post.

    cara menormalkan penglihatan yang buram
    cara mengatasi maag saat hamil
    cara mengobati sakit perut bagian kanan bawah
    cara mengobati sakit pinggang sebelah kanan
    cara mengobati ambeien atau wasir secara alami
    cara menyembuhkan kejang kejang
    cara menghilangkan cairan di paru paru

    ReplyDelete
  29. Hi,
    Your article is very informative and has a lot of information. I really like your effort, keep posting.
    blur photo editor 2019

    ReplyDelete
  30. I am really enjoyed to use the blog provided services for good education. These educational reviews are so much helpful to all our new blog writers and essay editors. These are all improves our student knowledge
    phd dissertation Writing Service uk

    ReplyDelete
  31. A very awesome blog post. We are really grateful for your blog post. You will find a lot of
    approaches after visiting your post.
    rrbgroupdresult-2019.in

    ReplyDelete
  32. http://get-spscripts.com/2010/07/adding-groups-with-permission-levels-to.html

    ReplyDelete
  33. Hi to everybody, here everyone is sharing such sarkari result
    knowledge, so it’s fastidious to see this site, jobnotifys.inand I used to visit this blog daily

    ReplyDelete
  34. The article is very interesting. And I also want to share articles about health, I'm sure this will be useful. Read and share it. Thank you very much :)

    Cara Menghilangkan Milia di Wajah
    Inilah Penyebab Kamu Telat Datang Bulan
    Cara Alami Mengatasi Radang Panggul

    ReplyDelete
  35. Students who have participated in UP plus two {+2} and X Class Supply exams are now looking for the SMS Based result details online at the internet. Students all of you know that Board will publish Senior Secondary & Higher Secondary Supply Exam Result in August / September 2019 at official web portal.

    ReplyDelete