The
PowerShell code below creates SharePoint groups mentioned in xml file within a
site and assigns the relevant permissions level to each. It will also configure
the groups to allow any member to edit the membership and show how to add users
into the newly created groups.
PowerShell Script
# Get Site and Web objects
Add-PSSnapin Microsoft.Sharepoint.Powershell
$filePath="D:\XmlFilePath\Groups.xml"
$site = Get-SPSite "https://mytenant.sharepoint.com/sites/mysitecollection"
$web = $site.RootWeb
write-host "Site Collection URL: "
$site.Url
write-host "Xml file path: "
$filePath
# Get XML file containing groups and associated users
$groupsXML = [xml] (Get-Content ($filePath))
# 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)
{
write-host "Creating Group -
" $_.name
# 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
write-host "Adding Users to the Group"
$group.Name
$_.Users.User
| ForEach-Object {
$group.Users.Add($_, "", "", "")
}
# Create a new assignment (group and
permission level pair) which will be added to the web object
write-host
"Creating new assignment for group" $group.Name
$groupAssignment = new-object
Microsoft.SharePoint.SPRoleAssignment($group)
# Get the permission levels to apply to the
new group
write-host "Permission Level"
$_.permissionlevel
$roleDefinition =
$web.Site.RootWeb.RoleDefinitions[$_.permissionlevel]
# Assign the appropriate permission level to
group
$groupAssignment.RoleDefinitionBindings.Add($roleDefinition)
# Add
the group with the permission level to the site
$web.RoleAssignments.Add($groupAssignment)
$web.Update()
write-host
"--------" $group.Name "Group Added to the site"
"--------"
}
# Dispose of Web
and Site objects
$web.Dispose()
$site.Dispose()
Xml File Format
<User>
domain\UserId </User>
<User>
domain\UserId </User>
</Users>
</Group>
<User>
domain\UserId </User>
<User>
domain\UserId </User>
</Users>
</Group>
</Groups>
No comments:
Post a Comment