Thursday, 1 July 2010

Creating multiple SharePoint groups and adding users with PowerShell

One of the great features in PowerShell is the ability to read an XML file and traverse the DOM nodes using a very simple dot notation. An example is the script below, which uses an XML file to modify and create SharePoint groups, adding their corresponding users. First the XML file:

<?xml version="1.0"?>
<Groups>
    <Group name="Approvers" description="">
        <Users>
            <User>DOMAIN\pchilds</User>
            <User>DOMAIN\tsmith</User>
        </Users>
    </Group>
    <Group name="HR" description="Team responsible for company Human Resources">
        <Users>
            <User>DOMAIN\jdavies</User>
            <User>DOMAIN\pjackson</User>
        </Users>
    </Group>
</Groups>

In this scenario, we are not just creating new groups, but also adding users to existing groups (“Approvers” in the example above). If the users already exists in a group, the script will just continue and add the next one:

#Get Site and Web objects
$site = Get-SPSite “http://portal”
$web = $site.RootWeb

#Get XML file containing groups and associated users
$groupsXML = [xml] (Get-Content ("C:\Path\Groups.XML"))

#Walk through each group node defined in the XML file
$groupsXML.Groups.Group | ForEach-Object {
    #Check to see if SharePoint group already exists in the site collection
    if ($web.SiteGroups[$_.name] -eq $null)
    {
        #If the SharePoint group doesn't exist already - create it from the name and description values at the node
        $newGroup = $web.SiteGroups.Add($_.name, $web.CurrentUser, $null, $_.description)
    }

    #Get SharePoint group from the site collection
    $group = $web.SiteGroups[$_.name]

    #Add the users defined in the XML to the SharePoint group
    $_.Users.User | ForEach-Object {
        $group.Users.Add($_, "", "", "")
    }
}

#Dispose of Web and Site objects
$web.Dispose()
$site.Dispose()

The script connects to the <Group /> node defined in the XML file with the line $groupsXML.Groups.Group and then uses the ForEach-Object statement to walk through each one. It detects if the group already exists – if not it creates a new one using the name and description defined at the node – and then walks through each <User /> node to add the users. Note the way the dot notation is used to access various parts of the XML node tree and how the “$_” syntax is used to call the node in context and its associated values.

59 comments:

  1. Thanks
    Some improvements - in SP2010 instead of $group.Users.Add you can use $group.AddUser(...), it must work more faster, if you are going to add many users.

    ReplyDelete
  2. Can you tell me where created the groups by using this script?
    I did not see in site permission list.

    ReplyDelete
  3. Thanks Phil for all your great job.

    ReplyDelete
  4. One update on line 2:
    $site = Get-SPSite “http://portal”

    This works great as long as the site is the Root Site Collection of WebApp. If you have site collections within the WebApp, you cannot add them using name - for example

    $site = Get-SPSite “http://portal/managedpath/sitecollection2” *does not work*

    Instead you can get the Site Collection ID and use the script as follows (no quotes or brackets):

    $site = Get-SPSite [SiteID_GUID]

    ReplyDelete
  5. You are using a built-in SharePoint Permission Level. Can a new group be added to a custom permission level at [group] creation time?

    ReplyDelete
  6. Hi!

    How to add permissions in the code?

    ReplyDelete
  7. Hi,

    How to add Read Permission level to the New Group

    ReplyDelete
  8. Replies
    1. I love how you still write and share about your day and experiences! You feel like such a real, nice, and humble person because of this!

      What Is SEO / Search Engine Optimization? | Master Of Seo


      Delete

  9. that may be the end of this write-up. Here you will obtain some web pages that we assume youll enjoy,
    just click the links over
    Here My Website :

    - Mesin Es Krim -
    - Mesin Es Krim Mrah

    ReplyDelete
  10. we like to honor lots of other internet web sites around the internet, even when they arent linked to us,
    by linking to them. Under are some webpages worth checking out
    Here My Website :

    - Sewa Mobil -
    - Mobil Jakarta
    - Rental Mobil Jakarta

    ReplyDelete
  11. Digital massage therapy chairs assist to boost
    the body’s blood stream flow, which possesses a few benefits.

    ReplyDelete
  12. I’m gone to inform my little brother, that he
    should also pay a quick visit this website on regular basis to obtain updated from latest news.

    ReplyDelete
  13. Hi there colleagues, its fantastic article regarding educationand completely defined,
    keep it up all the time.

    ReplyDelete
  14. that may be the end of this write-up. Here you will obtain some web pages that we assume youll enjoy, just click the links over....

    ReplyDelete
  15. Dreary Day

    It was a dreary day here yesterday, so I just took to messing around on the internet and found

    ReplyDelete
  16. we like to honor numerous other world wide web web pages around the web,
    even though they arent linked to us, by linking to them. Below are some webpages worth checking out

    ReplyDelete
  17. we like to honor numerous other world wide web web pages around the web,
    even though they arent linked to us, mobil murah 2017 by linking to them. mobil 7 penumpang
    Below are some webpages worth checking out

    ReplyDelete
  18. I could hardly abandon your web site just before suggesting we particularly cherished the common info a person offer on your own visitors? Will be usually yet again routinely to analyze cross-check completely new posts

    Master SEO Jakarta | Master SEO Indonesia | Master SEO Malaysia

    ReplyDelete
  19. We are really grateful for your blog post. You will find a lot of approaches

    ReplyDelete
  20. Fresh thoughts, fresh view on the subject..!!

    ReplyDelete
  21. Now I know that I was reading a blog with a post that is very commete. Thank you for sharing the information you post. I just subscribe to your blog. This is a great blog.

    ReplyDelete
  22. Awesome review, I am a major devotee to remarking on web journals to educate the web journal scholars realize that they've added something beneficial to the internet!.

    ReplyDelete
  23. That is a very goodd tip particularly to those new to the blogosphere. Simple but very accurate information… Appreciate yyour sharing this one. A must rewd post!

    ReplyDelete
  24. you are in reality a just right webmaster. The web site loading speed is amazing. It seems that you’re doing any distinctive trick. Furthermore, The contents are masterwork. you’ve performed a wonderful job on this subject!

    ReplyDelete
  25. Article writing is also a excitement, if you know afterward you can write otherwise it is complex to write.

    ReplyDelete
  26. That is a very goodd tip particularly to those new to the blogosphere. Simple but very accurate information… Appreciate yyour sharing this one. A must rewd post!

    ReplyDelete
  27. Good day! I know this is kind of off topic but I was wondering which blog platform are you using for this site?I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.my weblog;

    ReplyDelete
  28. I like your link because it contains lots of interesting information

    ReplyDelete
  29. the article is good I like and also easy to understand I like your article

    ReplyDelete
  30. Article writing is also a excitement, if you know afterward you can write otherwise it is complex to write.

    ReplyDelete
  31. I completely agree with you. Career planning is a lifelong process in selecting an occupation. Many thanks for sharing this great Tips & Career Suggestions. I liked reading this article and I will be sharing this with my team of professional who I am sure love to read similar articles here on this website.

    ReplyDelete
  32. I am really thankful to the holder of this web site who has shared this great article at here.

    ReplyDelete
  33. The information mentioned in the write-up are a information of the most effective

    ReplyDelete

  34. 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
  35. Thank you for visiting, thank you for giving us the information we need, do not forget to visit our page or website to share information about health thanks.
    Obat Neuropati di apotek
    Obat Sesak Nafas Alami
    I can only express a word of thanks. Because with the content on this blog I can add knowledge I, thank has been sharing this information. Do not forget to visit our website to share information and knowledge about health.
    obat batu ginjal alami
    obat syringoma

    ReplyDelete
  36. thank has been sharing this information. Do not forget to visit our website to share information and knowledge about health.
    cara mengobati busung air
    cara mengobati mag kronis
    obat penyakit hisprung
    obat radang sumsum tulang belakang
    obat penyakit batu empedu

    ReplyDelete
  37. Thank you for visiting, thank you for giving us the information we need, do not forget to visit our page or website to share information about health thanks.
    obat gudik Scabies
    obat balas bogo
    cara mengatasi milia
    cara menghilangkan balas bogo

    ReplyDelete
  38. Thank you for visiting, thank you for giving us the information we need, do not forget to visit our page or website to share information about health thanks.
    obat pityriasis alba paling ampuh
    cara mengobati sakit pinggang
    obat gusi bengkak
    obat kelenjar air liur

    ReplyDelete
  39. Thank you for visiting, thank you for giving us the information we need, do not forget to visit our page or website to share information about health thanks.
    Agen jelly gamat QnC cibeureum tasikmalaya
    obat gondongan alami
    cara mengobati sakit pnggang
    cara mengatasi sakit perut sebelah kiri / kanan

    ReplyDelete
  40. It is a time consuming process to locate a legitimate, high-quality designer Michael Kors Handbags On Sale at a decent price. One brand name that is sought after is the Michael Kors Bags On Sale. Anywhere you see high demand you will find people out to make a quick buck.

    ReplyDelete
  41. It is a time consuming process to locate a legitimate, high-quality designer Michael Kors Handbags Clearance at a decent price. One brand name that is sought after is the Michael Kors Outlet Store. Anywhere you see high demand you will find people out to make a quick buck.

    ReplyDelete
  42. Thank you for visiting, thank you for giving us the information we need, do not forget to visit our page or website to share information about health thanks.
    Obat Neuropati di apotek
    Obat Sesak Nafas Alami
    obat batu ginjal alami
    obat syringoma

    ReplyDelete
  43. Wonderful blog
    It’s really a nice and helpful piece of information. I’m satisfied that you just shared this helpful information with us. Please stay us informed like this. Thanks for sharing.

    agen bola tangkas
    Nonton movie online
    situs bola tangkas

    ReplyDelete
  44. The post is written in very a good manner and it contains many useful information for me. Thank you very useful information admin, and pardon me permission to share articles here may help :

    obat benjolan di bawah rahang
    obat amandel bengkak
    obat benjolan di ketiak
    obat tumor ginjal
    obat lambung bocor
    obat borok di kepala

    ReplyDelete
  45. Designer Exposure es un buen lugar para comprar su Bolsos Michael Kors original.
    The Woven Tote es también una selección impresionante en el Bolsos Michael Kors Baratos.
    Bolso de alta calidad que debe contemplar absolutamente un Bolsos Michael Kors Outlet.
    Du kommer att upptäcka en handfull detaljer som du kan förvänta dig att komma över på en vanlig Michael Kors Rea.
    Du kan hitta ett antal platser som ger Väska Michael Kors.
    Sortimentet är fantastiskt för alla som letar efter en MK Väska.
    Håll dina ögon öppna för den här säsongens val som kommer att presenteras under bara några månader och det kommer utan tvekan att bli spektakulärt.

    ReplyDelete
  46. I can only express a word of thanks. Because with the content on this blog I can add knowledge I, thank has been sharing this information. Do not forget to visit our website to share information and knowledge about health.
    Obat Jantung Berdebar Walatra Sehat raga
    Cara Mengatasi Insomnia

    ReplyDelete