Create SPGroup in PowerShell
By Anatoly Mironov
Thanks to Ryan for sharing powershell functions. I used New-SPGroup which I altered. Now You can define which permissions will be given to the new group. You can even create groups without default users. Here it comes:
function New-SPGroup {
<#
.Synopsis
Use New-SPGroup to create a SharePoint Group.
.Description
This function uses the Add() method of a SharePoint RoleAssignments property in an SPWeb to create a SharePoint Group.
.Example
New-SPGroup -Web http://intranet -GroupName "Test Group" -OwnerName DOMAIN\\User -MemberName DOMAIN\\User2 -Description "My Group" -Role "Read"
This example creates a group called "Test Group" in the http://intranet site, with a description of "My Group". The owner is DOMAIN\\User and the first member of the group is DOMAIN\\User2 and adds "Limited Access".
C:\\PS>New-SPGroup -Web http://intranet -GroupName "Test Group" -OwnerName DOMAIN\\User -MemberName DOMAIN\\User2 -Description "My Group" -Role "Read"
This example creates a group called "Test Group" in the http://intranet site, with a description of "My Group". The owner is DOMAIN\\User and the first member of the group is DOMAIN\\User2 and adds "Read" access.
Pay attention to the role definition names. They must be provided in the language of your site.
.Notes
Name: New-SPGroup
Author: Ryan Dennis, Anatoly Mironov
Last Edit: 2012-11-05
Keywords: New-SPGroup, spgroup, permissions
.Link
http://www.sharepointryan.com
http://twitter.com/SharePointRyan
https://sharepointkunskap.wordpress.com
.Inputs
None
.Outputs
None
#Requires -Version 2.0
#>
\[CmdletBinding()\]
Param(
\[Microsoft.SharePoint.PowerShell.SPWebPipeBind\]$Web,
\[string\]$GroupName,
\[string\]$OwnerName,
\[string\]$MemberName,
\[string\]$Role,
\[string\]$Description
)
$SPWeb = $Web.Read()
if ($SPWeb.SiteGroups\[$GroupName\] -ne $null){
throw "Group $GroupName already exists!"
}
if ($Role) {
$roleDefinition = $SPWeb.RoleDefinitions\[$Role\]
if (!$roleDefinition) {
throw "Role Definition $Role doesn't exist!"
}
}
if ($SPWeb.Site.WebApplication.UseClaimsAuthentication){
$op = New-SPClaimsPrincipal $OwnerName -IdentityType WindowsSamAccountName
$owner = $SPWeb | Get-SPUser $op
if ($MemberName) {
$mp = New-SPClaimsPrincipal $MemberName -IdentityType WindowsSamAccountName
$member = $SPWeb | Get-SPUser $mp
}
}
else {
$owner = $SPWeb | Get-SPUser $OwnerName
if ($MemberName) {
$member = $SPWeb | Get-SPUser $MemberName
}
}
$SPWeb.SiteGroups.Add($GroupName, $owner, $member, $Description)
$SPGroup = $SPWeb.SiteGroups\[$GroupName\]
$roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($SPGroup)
if ($Role) {
$roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
}
$SPWeb.RoleAssignments.Add($roleAssignment)
$SPWeb.Dispose()
return $SPGroup
}