PowerShell: SharePoint - Creating Role Definition and Applying to a Group

Updated on 5/29/2013
$web = Get-SPWeb http://dmg-10
$permname = "PermName1"

#create role def
$roledef = New-Object Microsoft.SharePoint.SPRoleDefinition
$roledef.BasePermissions = [Microsoft.SharePoint.SPBasePermissions]::FullMask -bxor [Microsoft.SharePoint.SPBasePermissions]::ManageSubwebs
#[enum]::GetValues([Microsoft.SharePoint.SPRights]) | ?{$_.value__ -band $roledef.BasePermissions}
$roledef.Name = $permname
$web.RoleDefinitions.Add($roledef)
$web.Update()

#remove other role assignments (ie. Full Control)
$web.RoleAssignments.Remove($web.AssociatedOwnerGroup)
$web.AssociatedOwnerGroup.Update()
$web.Update()

#assign role def to group
$roledef = $web.RoleDefinitions[$permname]
$roleassign = new-object Microsoft.SharePoint.SPRoleAssignment($web.AssociatedOwnerGroup)
$roleassign.RoleDefinitionBindings.Add($roledef);
$web.RoleAssignments.Add($roleassign)
$web.AssociatedOwnerGroup.Update()
$web.Update()