Create a site collection in SharePoint Online with this powershell script. This code snippet accepts site template , storage and resource quota and time zone as configurable input parameters for creation of site collection
Pre-requisite:
1. Install SharePoint online management shell
2. The Sharepoint.Client.* dll’s should exist in the local drive. Modify the path in the Power Shell script file to point the dll’s in local drive as shown in below image
3. If necessary, can modify the Storage quota, Resource quota, Time Zone and Template in the power shell script file as shown below.
4. The Images and Themes folder should exist in the same folder along with the Power shell script.
5. The site will get created in this format – MSXXX. E.g., MS001 , MS876. (This can also be changed in the script)
Code Snippet
Import-Module "C:Program FilesSharePoint Online Management ShellMicrosoft.Online.SharePoint.PowerShellMicrosoft.Online.SharePoint.PowerShell.dll"
Add-Type -Path "C:SPO ISAPI DLLMicrosoft.SharePoint.Client.dll"
Add-Type -Path "C:SPO ISAPI DLLMicrosoft.SharePoint.Client.Runtime.dll"
$siteTemplate = ‘STS#0’ #Site template
$storageQuota ='1024' #Site Collection Staorage Quota
$resourceQuota ='100' #Site Collection Resource Quota
$timeZone ='13' #Time Zone
################################## Dont modify the code beyond this line ####################################
$siteCollectionCount = 0
$adminUrl = Read-Host -Prompt 'Enter Tenant Admin Url' #Url of sharepoint online tenant admin site
$SCadmin1 = Read-Host -Prompt 'Enter the 1st Site Collection Admin group' #Admins to be added to sharepoint online tenant site
$SCadmin2 = Read-Host -Prompt 'Enter the 2nd Site Collection Admin group' #Admins to be added to sharepoint online tenant site
[int]$siteStartno = Read-Host -Prompt 'Enter the Site Start No' #Site collections will be created within this start and end number.
[int]$siteEndno = Read-Host -Prompt 'Enter the Site End no'
$owner = Read-Host -Prompt 'Enter the Tenant Admin Login Name' #Admin of sharepoint online tenant admin site
$response = Read-host -Prompt "Enter the Tenant Admin password" -AsSecureString
$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($response))
function Create-AZSiteCollections
{
param (
[Parameter(Mandatory=$true,Position=1)]
[System.String]$adminUrl,
[Parameter(Mandatory=$true,Position=1)]
[System.String]$owner,
[Parameter(Mandatory=$true,Position=1)]
[System.String]$SCadmin1,
[Parameter(Mandatory=$true,Position=1)]
[System.String]$SCadmin2,
[Parameter(Mandatory=$true,Position=1)]
[int]$siteStartno,
[Parameter(Mandatory=$true,Position=1)]
[int]$siteEndno
)
$tenantUrl = $adminUrl.Replace("-admin","")
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($owner, $securePassword)
$connectCredentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $owner, $securePassword
try
{
Connect-SPOService -Url $adminUrl -Credential $connectCredentials
try
{
For($sitecount = $siteStartno; $sitecount -le $siteEndno ; $sitecount++)
{
if($sitecount -le 999)
{
$siteNumber = [String]$sitecount
$titlesuffix = ""
if($siteNumber.length -eq 1) #adding suffix in the format starting from MS000 to MS999
{
$titlesuffix = "MS00" + $siteNumber
}
elseif($siteNumber.length -eq 2)
{
$titlesuffix = "MS0" + $siteNumber
}
elseif($siteNumber.length -eq 3)
{
$titlesuffix = "MS" + $siteNumber
}
$newsitecollectionUrl = $tenantUrl + "/sites/" + $titlesuffix
$newTitle = $titlesuffix
Write-Host $newTitle ' - site collection is getting created.... please wait ....' #Creating site collection
New-SPOSite -Owner $owner -StorageQuota $storageQuota -Url $newsitecollectionUrl -ResourceQuota $resourceQuota -Template $siteTemplate -TimeZoneID $timeZone -Title $newTitle
Write-Host $newTitle ' - site collection created.' -ForegroundColor Green
$siteCollectionCount++
Write-Host $newTitle ' - Adding site collection administrators....'
$ownerGroup = get-spoSitegroup -site $newsitecollectionUrl | where {$_.title -like "*Owners"}
$ownertitle = $ownerGroup.title
add-SPOuser -site $newsitecollectionUrl -LoginName $SCadmin1 -group $ownerTitle #Adding site collection admins
add-SPOuser -site $newsitecollectionUrl -LoginName $SCadmin2 -group $ownerTitle
Write-Host $newTitle ' - Site collection administrators added.' -ForegroundColor Green
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($newsitecollectionUrl) # connect/authenticate to SharePoint Online and get ClientContext object..
$ctx.Credentials = $credentials
if (!$ctx.ServerObjectIsNull.Value)
{
Write-Host "Connected to " $newsitecollectionUrl -ForegroundColor Green
}
Set-SiteThemeAndLogo -ctx $ctx -newSiteCollection $newsitecollectionUrl
}
else {
Write-Host 'Contact your administrator to create more than 999 site collections.' -ForegroundColor Red }
}
}
catch{
Write-Host "Error creating SharePoint site collections" -ForegroundColor Red
}
}
catch{
Write-Host "Error connecting to SharePoint Online services" -ForegroundColor Red
}
Write-Host $siteCollectionCount 'Site Collections created' -ForegroundColor Green
}
function Set-SiteThemeAndLogo
{
param (
[Parameter(Mandatory=$true,Position=1)]
[Microsoft.SharePoint.Client.ClientContext]$ctx,
[Parameter(Mandatory=$true,Position=1)]
[System.String]$newSiteCollection
)
[System.IO.FileInfo]$imageSourcePath = "Images/imgAZLogo.png"
[System.IO.FileInfo]$Folder = "Themes/XXXX.spcolor"
$themeTitle = "XXXX"
$siteAssetlist = $ctx.Web.Lists.GetByTitle("Site Assets"); # get the site assets list
$ctx.Load($siteAssetlist.RootFolder)
$imageFolder = $siteAssetlist.RootFolder.Folders.Add("Images")
$ctx.Load($imageFolder)
$themesList = $ctx.web.GetCatalog(123); # get the Theme list
$themesListFolder = $themesList.RootFolder
$ctx.Load($themesListFolder);
$ctx.ExecuteQuery();
Set-SiteLogo -ctx $ctx -imageFolder $imageFolder -imageSourcePath $imageSourcePath
Set-SiteTheme -ctx $ctx -themesListFolder $themesListFolder
Set-ComposedEntry -ctx $ctx -themeTitle $themeTitle -newSiteCollection $newSiteCollection
$ctx.ExecuteQuery()
}
function Set-SiteLogo
{
param (
[Parameter(Mandatory=$true,Position=1)]
[Microsoft.SharePoint.Client.ClientContext]$ctx,
[Parameter(Mandatory=$true,Position=1)]
[Microsoft.SharePoint.Client.Folder]$imageFolder,
[Parameter(Mandatory=$true,Position=1)]
[System.IO.FileInfo]$imageSourcePath
)
$folderRelativeUrl = $imageFolder.ServerRelativeUrl
try {
$fileUrl = $folderRelativeUrl + "/imgAZLogo.png"
Write-Host "Uploading site Logo file ..."
[Microsoft.SharePoint.Client.File]::SaveBinaryDirect($ctx, $fileUrl, $imageSourcePath.OpenRead(), $true)
Write-Host "site logo file has been uploaded succesfully. Url: $fileUrl" -ForegroundColor Green
}
catch {
write-host "An error occured while uploading file imgAZLogo.png" -ForegroundColor Red
}
$ctx.web.SiteLogoUrl = $fileUrl;
$ctx.web.Update();
}
function Set-SiteTheme
{
param (
[Parameter(Mandatory=$true,Position=1)]
[Microsoft.SharePoint.Client.ClientContext]$ctx,
[Parameter(Mandatory=$true,Position=1)]
[Microsoft.SharePoint.Client.Folder]$themesListFolder
)
$themefolder = $ctx.web.GetFolderByServerRelativeUrl($themesListFolder.ServerRelativeUrl + "/15")
$fileUrl = $themesListFolder.ServerRelativeUrl +"/15/XXXXX.spcolor"
try {
Write-Host "Uploading file XXXXX.spcolor ...."
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
Foreach ($File in (dir $Folder -File))
{
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
try
{
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $fileUrl
$Upload = $themefolder.Files.Add($FileCreationInfo)
$ctx.Load($Upload)
$ctx.ExecuteQuery()
}
catch
{
write-host "An error occured while uploading file XXXXX.spcolor" -ForegroundColor Red
}
finally
{
$FileStream.Dispose()
}
}
Write-Host "File XXXXX.spcolor has been uploaded succesfully. Url: $fileUrl" -ForegroundColor Green
$fonturl = Out-Null
$backgroundurl = Out-Null
$ctx.Web.ApplyTheme( $fileUrl, $fonturl, $backgroundurl , $True);
$ctx.Web.update()
$ctx.Load($ctx.Web)
Write-Host "Theme XXXXX has been set to the site" -ForegroundColor Green
}catch {
write-host "An error occured while setting the theme - XXXXX.spcolor" -ForegroundColor Red }
}
function Set-ComposedEntry
{
param (
[Parameter(Mandatory=$true,Position=1)]
[Microsoft.SharePoint.Client.ClientContext]$ctx,
[Parameter(Mandatory=$true,Position=1)]
[System.String]$themeTitle,
[Parameter(Mandatory=$true,Position=1)]
[System.String]$newSiteCollection
)
try
{
$relativeurl = $newSiteCollection.Split("/")
Write-Host "Adding entry to Composed Look List...." -ForegroundColor Green
$composedList = $ctx.web.GetCatalog(124); # get the Composed Look list
$itemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$newItem = $composedList.AddItem($itemCreateInfo)
$newItem["Title"] = $themeTitle;
$newItem["Name"] = $themeTitle;
$newItem["MasterPageUrl"] = "/" +$relativeurl[$relativeurl.length-2]+ "/" + $relativeurl[$relativeurl.length-1] + "/_catalogs/masterpage/seattle.master";
$newItem["ThemeUrl"] = "/" + $relativeurl[$relativeurl.length-2]+ "/" + $relativeurl[$relativeurl.length-1] + "/_catalogs/theme/15/XXXXX.spcolor" ;
$newItem["DisplayOrder"] = 180;
$newItem.Update();
Write-Host "Entry added to Composed Look List successfully" -ForegroundColor Green
}
Catch {
write-host "An error occured adding entry to Composed Look List" -ForegroundColor Red }
}
Create-AZSiteCollections -adminUrl $adminUrl -owner $owner -SCadmin1 $SCadmin1 -SCadmin2 $SCadmin2 -siteStartno $siteStartno -siteEndno $siteEndno
Leave a comment