Blog about anything related to my learnings
  • About
  • posts
bluesky
Blog about anything related to my learnings
POSTS

This script adds a content type from the content type hub to the “Documents” library within a SharePoint site.

    [string]$ClientId = "xxxxx"
    [string]$sitesFilesPath ="C:\Users\xx\Documents\scripts\HubSites.csv"
    [string]$CertPath = "C:\Users\xx\ertificates\ReshmeeCertPnP.pfx"
    [string]$TenantUrl = "https://contoso.sharepoint.com"
    $ContentTypes = @("Test Record", "Test 1 Record", "Document Set")
    [string]$TenantName = "contoso"
    $CertPassword = Read-Host "Please enter Certificate Password:" -AsSecureString
    
    [string]DocumentSetFeatureId = "3bae86a2-776d-499d-9db8-fa4cdc7884f8"

#$csvPath = Join-Path $directorypath $sitesFiles
$sites = Import-Csv -Path $sitesFilesPath
if (-not $sites -or $sites.Count -eq 0) {
    write-host "No rows found in CSV: $sitesFilesPath" -BackgroundColor Red
    throw "Empty CSV."
}

# Function to check if a content type exists on site"
function CheckContentTypeExists {
    param (
        [string]$ContentTypeName,
        [string]$SiteUrl
    )
    
    $pnpConnection = Connect-PnPOnline -ClientId $clientId -CertificatePath $CertPath -CertificatePassword $CertPassword -Url $SiteUrl -Tenant "$($TenantName).onmicrosoft.com"
    
    try {
        # Get the content types from the site
        $contentTypes = Get-PnPContentType -Connection $pnpConnection
        # Check if the content type exists
        $contentTypeExists = $contentTypes | Where-Object { $_.Name -eq $ContentTypeName}
        return $contentTypeExists
    }
    catch {
        LogMessage "" "" "Error" "$($SiteUrl):Failed to check if the content type exists. $_"
        return $null
    }
 
}

# Function to add content type on site
function AddContentTypeToSite {
    param (
        [string]$SiteUrl
        [string]$ContentTypeName
    )
    try 
    {
        Write-Host $SiteUrl "Info" "Adding content type '$($ContentTypeName)' to site"
        if(!$HubContentTypes)
        {
            $HubContentTypes = Get-PnPCompatibleHubContentTypes -WebUrl $TenantUrl
        }
        $ContentTypeDetails = $HubContentTypes | Where-Object { $_.Name -contains $ContentTypeName }
        Add-PnPContentTypesFromContentTypeHub -ContentTypes $ContentTypeDetails.Id -Site $SiteUrl | out-null
        Write-host $SiteUrl "Success" "Successfully added content type '$($ContentTypeName)' to site" -BackgroundColor Green
    }
    catch {
        Write-host $SiteUrl "Error" "Error while adding content type '$($ContentTypeName)' to site. $_" -BackgroundColor Green
    }
}

function ApplyContentTypeToLibrary {
    param (
        [string]$library,
        [string]$SiteUrl
    )
    
    $pnpConnection = Connect-PnPOnline -ClientId $clientId -CertificatePath $CertPath -CertificatePassword $CertPassword -Url $SiteUrl -Tenant "$($TenantName).onmicrosoft.com" -ReturnConnection

        # Loop through each content type and add it to the library
        foreach ($contentType in $ContentTypes) {
            try {
                Add-PnPContentTypeToList -List $library -ContentType $contentType -Connection $pnpConnection -ErrorAction Stop
                Write-host $SiteUrl "Success" "Content type '$($contentType)' applied on library '$($library)'" -BackgroundColor Green
            }
            catch {
                Write-host $SiteUrl "Error" "Failed to apply content type '$($contentType)' on library '$($library)'. $_" -BackgroundColor Green
            }
        }
        #Set Default Content Type of the List
        Set-PnPDefaultContentTypeToList -List $library -ContentType "Test Record" -ErrorAction SilentlyContinue

        Remove-PnPContentTypeFromList -ContentType "Document" -List $library -Connection $pnpConnection -ErrorAction SilentlyContinue
    }
            foreach($site in $sites)
            {
                $siteUrl     = $site.SiteUrl
                Write-Host "Connecting to target site..." 
                Connect-PnPOnline -ClientId $ClientId -CertificatePath $CertPath -CertificatePassword $certPassword `
                -Url $siteUrl -Tenant "$($TenantName).onmicrosoft.com" -ValidateConnection
                # Activate the Document Sets feature 
                Enable-PnPFeature -Identity $DocumentSetFeatureId -Scope Site -Force
                Write-host $SiteUrl "Success" "Successfully set up document set feature"
                # Add document set feature to site in case there are changes at hub
                Add-PnPContentTypesFromContentTypeHub -ContentTypes "0x0120D520" -Site $SiteUrl

                Write-host $SiteUrl "Adding content types to site - $($SiteUrl)"
                # Loop through each content type and add it to the library
                foreach ($contentType in $ContentTypes) 
                {
                    #LogMessage "Checking for content type '$($contentType)' if it exists on site" "Info"
                    $contentTypeExists = CheckContentTypeExists -ContentTypeName $contentType -SiteUrl $siteURL
                    if($contentTypeExists) {
                        Write-Host  $SiteUrl "Content type '$($contentType)' exists on site"
                    }
                    else {
                        Write-Host $SiteUrl "Adding content type '$($contentType)' on site:$($SiteURL)"
                        AddContentTypeToSite -SiteUrl $SiteUrl -TenantUrl $TenantUrl -ContentTypeName $contentType
                    }
                }

                # Set content type to library
                ApplyContentTypeToLibrary -library "Documents" -SiteUrl $siteURL
            }
    © Blog about anything related to my learnings 2026
    bluesky