How to add an existing group to a newly created site through poweshell?
-
10-12-2019 - |
Question
I am creating sites through powershell and creating the groups for them. I have a situation where if the group is already existing group then I have to add that group to the site. Coz might be possible the site is not present and the group is present. For ex: the site name is "xyz" and the group name is "xyz_admin". Here if the group is already existing group while creating the site then I have to add it to the site.
I am adding the group like this:
Add-SPGroup.ps1 -url $url -Group ($webname+"_admins") -Role "Fuld kontrol" -Owner $global:loginName
but it gives me an error when the group is present.
Any help is appreciated in this aspect.
Thanks in advance.
Solution
if ($SPWeb.SiteGroups[$webname+"_admins"] -ne $null){
Write-Host "Group "$GroupName" already exists!"
$SPWeb.AssociatedGroups.Add($SPWeb.SiteGroups[$webname+"_admins"]);
$desiredGroup = $SPWeb.SiteGroups[$webname+"_admins"]
$roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($desiredGroup)
$role = $SPWeb.RoleDefinitions["Contribute"]
$roleAssignment.RoleDefinitionBindings.Add($role)
$SPWeb.RoleAssignments.Add($roleAssignment)
$SPWeb.Update()
$SPWeb.Dispose()
Break;
} 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]
$SPWeb.RoleAssignments.Add($SPGroup)
}
Ref:
Powershell to create Sharepoint groups
Adding a security group to a SharePoint site via PowerShell
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange