PowerShell Script site creation Using SharePoint Online Management Shell

# Connect to SharePoint Online
$AdminURL = "https://yourtenant-admin.sharepoint.com"
$Credential = Get-Credential
Connect-SPOService -Url $AdminURL -Credential $Credential

# Import site information from the CSV file
$SiteCollections = Import-Csv -Path "C:\Path\To\Your\CSVFile.csv"
$HubSiteId = "YOUR_HUB_SITE_ID"  # Replace with your Hub site ID

# Define document libraries based on templates
$DocumentLibraryNames = @{
    "STS#0" = @("TeamDocuments", "SharedDocs", "ProjectFiles")
    "STS#1" = @("Announcements", "MediaLibrary", "MarketingDocs")
    "STS#2" = @("ProjectDocuments", "ResearchDocuments", "Reports")
    "STS#3" = @("PolicyDocuments", "Templates", "Archive")
}

foreach ($site in $SiteCollections) {
    $Title = $site.Title
    $URL = $site.Url
    $Owner = $site.Owner
    $Template = $site.Template

    # Create the site collection (if it doesn't exist)
    try {
        New-SPOSite -Url $URL -Owner $Owner -Title $Title -Template $Template -NoWait
        Write-Host "Created site collection: $Title at $URL" -ForegroundColor Green
    } catch {
        Write-Host "Error creating site collection. It may already exist: $_" -ForegroundColor Red
        continue
    }

    # Delay to ensure the site is fully provisioned
    Start-Sleep -Seconds 30  # Adjust time as necessary based on your tenant's provisioning speed

    # Create Document Libraries based on the template
    if ($DocumentLibraryNames.ContainsKey($Template)) {
        foreach ($libraryName in $DocumentLibraryNames[$Template]) {
            # Create the Document Library
            New-SPOList -Title $libraryName -Template DocumentLibrary -Web $URL
            Write-Host "Document library created: $libraryName" -ForegroundColor Green

            # Optionally add to Quick Launch (this step requires another step)
            $QuickLaunchItem = New-Object Microsoft.SharePoint.Client.NavigationNodeCreationInformation
            $QuickLaunchItem.Title = $libraryName
            $QuickLaunchItem.Url = "$URL/$libraryName"
            $QuickLaunchItem.IsVisible = $true

            # Add the Quick Launch Item
            $Web = Get-SPOSite -Identity $URL
            $Web.Navigation.QuickLaunch.Add($QuickLaunchItem)
            $Web.Update()
            Write-Host "Added $libraryName to Quick Launch" -ForegroundColor Green
        }
    } else {
        Write-Host "No document libraries defined for the template: $Template" -ForegroundColor Yellow
    }

    # Associate the newly created site to the Hub site
    try {
        Set-SPOSite -Identity $URL -HubSiteId $HubSiteId
        Write-Host "Added $Title to Hub site with ID: $HubSiteId" -ForegroundColor Green
    } catch {
        Write-Host "Failed to add $Title to Hub site. Error: $_" -ForegroundColor Red
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *