Friday, May 18, 2012

Create groups in site collection using PowerShell

I guess you've been there before. A customer asks for creating several SharePoint groups and it all ends that you have to create several dozens of groups including adding members inside. There was useful STSADM command in SHP 2007 before but now we can do it with PowerShell. It's easy and fast.

There is already written cmdlet for this so only few tiny bits were needed to be tailored to have it as needed. What I wanted is to have CSV file as input with Group name, description, owner and members.

The existing cmdlet is from SharePointRyan Blog page, originally coming from well known guy Gary Lapointe. I've added few lines responsible for reading from the CSV file and also small try catch error clause to give you information when the file or script goes wrong.
Creates groups defined in the CSV file
autor: Jiri Manek -

CSV file structure
  Group  , Desc         ,  Owner      ,  Member
  Name   , Description  , domain\login, domain\login
  Name   , Description  , domain\login,

#Gary's and Ryan's function tailored
function global:New-SPGroup {
 Use New-SPGroup to create a SharePoint Group.
 This function uses the Add() method of a SharePoint RoleAssignments property in an SPWeb to create a SharePoint Group.
 Name: New-SPGroup
 Author: Ryan Dennis
 Last Edit: July 18th 2011
 Keywords: New-SPGroup
 $SPWeb = $Web.Read()
 if ($SPWeb.SiteGroups[$GroupName] -ne $null){
  Write-Host "Group "$GroupName" already exists!" 
 } else
  $owner = $SPWeb | Get-SPUser $OwnerName
  if ($MemberName -ne "") {  $member = $SPWeb | Get-SPUser $MemberName }
  $SPWeb.SiteGroups.Add($GroupName, $owner, $member, $Description)
  $SPGroup = $SPWeb.SiteGroups[$GroupName]

return $ErrMessage

$web_url = Read-Host "Type web URL"
$filename = Read-Host "Type file name (including path)"

$csv = Import-csv -path $filename
 if ($csv -ne $null) {
    foreach($line in $csv)
                   [string]$GroupName = $line.Group;
                   [string]$GroupDescription = $line.Desc;
                   [string]$GroupOwner = $line.Owner;
                   [string]$GroupMember = $line.Member;
       try {
                 New-SPGroup -Web $web_url -GroupName $GroupName -OwnerName $GroupOwner -MemberName $GroupMember -Description $GroupDescription;
                    Write-Host "SharePoint group" $line.Group "has been created."
       Catch [system.exception]
        Write-Host "Error occured - groups were not created.";
Just give it the CSV file and let it crunch it! ;-) If you find any issues or bugs, feel free to comment.

1 comment:

  1. Jiri,
    Can this powershell build groups for lists which does not inherit permissions from its parent site?