Create SharePoint Groups with PowerShell

It wasn't until I looked into this tweet that I realized there was no "New-SPGroup" type cmdlet that ships with SharePoint out of the box. Instead, we have to call the SiteGroups.Add operation on the web where we want to make the group. While this isn't terribly intuitive for people new to PowerShell, this post should help to walk you through it.

Firstly, we're adding groups to webs, not sites, so we need to identify the web where the group is going to exist. While groups are available site-wide, they're actually stored at the web level, which explains why when you create a subsite (a web), you get the three default groups created. Yes, I realize it's confusing that a web has a property of "SiteGroups", and a site doesn't--but that's just the way it is. Before we can do anything, we need to create a variable and save our web object into it.

$web = Get-SPWeb http://intranet

In addition to a title and description, we also need to specify the owner and any members of our group when we call the SiteGroups.Add operation; those users must be valid SPUser objects, not a "domainusername" string. To keep things simple for this example, let's assume they're the same person, since the owner is typically also a member of the group. We're going to create a user variable, and pipe our web object to the Get-SPUser cmdlet (with a user string). This will tell PowerShell to iterate through every user in our web until it finds the one we've specified, and save that SPUser object to our user variable.

$user = $web | Get-SPUser "domainusername"

Now that we have our user captured, we can go ahead and call the SiteGroups.Add operation, passing to it the title of the group, the owner of the group, the members of the group, and the description of the group (in that order).

$web.SiteGroups.Add("Group Name", $user, $user, "Group Description")

Now it's a simple matter of heading on over to your groups list and validating that it's there.

If, like Rebecca, you had a lot of these to do, you could store the details in a CSV file and handle your inputs from there. Let's assume you had a CSV with columns of "Web", "GroupName", "User", and "GroupDescription" that was stored in C:Groups.csv, we can make a simple script to loop through all of the lines in the Groups.csv file and create each group.

$groups = Import-CSV c:Groups.csv
foreach ($group in $groups) {
    $web = Get-SPWeb $group.Web
    $user = $web | Get-SPUser $group.User
    $web.SiteGroups.Add($group.GroupName, $user, $user, $group.GroupDescription)