PowerShell script to create bulk sub sites in modern site and associate group to that site

Technology Specialist
Published On :   26 Nov 2018
Visit Count
Today :  3    Total :   344

In this article, let us see how to create bulk sites by accessing csv in modern site and associate default group to that site.

 Write-Output -msg "Start : Module loading Process"
 $modulePath = "C:\Program Files (x86)\SharePointPnPPowerShellOnline\Modules\SharePointPnPPowerShellOnline"
 import-module ($modulePath + "\SharePointPnPPowerShellOnline.psd1")
 Add-Type -Path ($modulePath + "\SharePointPnP.PowerShell.Online.Commands.dll")
 Add-Type -Path ($modulePath + "\Microsoft.SharePoint.Client.dll")
 Add-Type -Path ($modulePath + "\Microsoft.SharePoint.Client.Runtime.dll")
 Add-Type -Path ($modulePath + "\Microsoft.Online.SharePoint.Client.Tenant.dll")
 Write-Output -msg "End : Module loading Process"
 $cred = Get-Credential
 $csv = import-csv -Path "D:\Scripts\SiteInput.csv"
 Clear-Content "D:\SiteCreationLog.txt"
 foreach($value in $csv)
 $URL= $TargetURL -replace $ParentURL+'/' 
 if($WebTemplate -eq "Team")
     #Connect to Site Collection       
     Connect-PnPOnline -Url $ParentURL -Credentials $cred
     #Create sub web with unique permissions
     New-PnPWeb -Title $Title -Url $URL -Description $Description -BreakInheritance -InheritNavigation -Template "STS#3"
     Connect-PnPOnline -Url $TargetURL -Credentials $cred
     $owner = (Get-PnPContext).Credentials.UserName
     #Create default groups for the new web
     $OwnerGroupName=$URL+" Owners"
     $MemberGroupName=$URL+" Members"
     $VisitorGroupName=$URL+" Visitors"
     $ownerGroup = New-PnPGroup -Title $OwnerGroupName -Owner $owner 
     Set-PnPGroup -Identity $ownerGroup -SetAssociatedGroup Owners
     Set-PnPGroupPermissions -Identity $ownerGroup -AddRole "Full Control"
     $memberGroup = New-PnPGroup -Title $MemberGroupName -Owner $owner
     Set-PnPGroup -Identity $memberGroup -SetAssociatedGroup Members
     Set-PnPGroupPermissions -Identity $memberGroup -AddRole "Edit"
     $visitorGroup = New-PnPGroup -Title $VisitorGroupName -Owner $owner
     Set-PnPGroup -Identity $visitorGroup –SetAssociatedGroup Visitors
     Set-PnPGroupPermissions -Identity $visitorGroup -AddRole "Read"
     $TargetURL+" PASS" | Out-File -FilePath D:\SiteCreationLog.txt -Append
     Write-Error "Invalid Template Name" 
     $TargetURL+" Invalid Template Name"| Out-File -FilePath D:\SiteCreationLog.txt -Append
 Write-Output $_.Exception.Message 
 $TargetURL+" "+$_.Exception.Message | Out-File -FilePath D:\SiteCreationLog.txt -Append

Hope this helps!