Inside PnP Include files in a template

 In a previous article I described how to create a template of a SharePoint site using the PnP provisioning framework. I also mentioned some restrictions of the framework. One of those restrictions is that files from SharePoint document libraries are not exported to the template by default.

In this article I'm showing how you can add files to your template nevertheless.

Images on pages are affected and will be missing

Let's take modern pages as an example of what can break when files are missing in the template. For some time now you have been able to format the header area of modern pages in different ways. One option is to upload a header image.

You hit the Upload button and choose a file:

Es wurde kein Alt-Text für dieses Bild angegeben.

SharePoint takes this file and copies it to a sub folder of the Site Assets library:

Es wurde kein Alt-Text für dieses Bild angegeben.

When you export this site as a template such images will be pointed to by the template file but the actual image files will be missing. That means the provisioned pages won't have a working header image.

Let's fix that.

Adding Images one by one

There is a PnP PowerShell cmdlet Add-PnPFileToProvisioningTemplate that does what we want:

  • download and save a file from SharePoint Online to a local folder
  • modify the template file to make sure provisioning works

We can use this cmdlet to download all files from the Site Assets library and add it to the template file like this:

Connect-PnPOnline -Url "https://tenant.sharepoint.com/sites/templatesite"
$list = Get-PnPList "SiteAssets"
# get all files from SiteAssets, skip folders
$files = Get-PnPListItem -List $list -Fields Id,FileRef | ? { $_.FileSystemObjectType -ne "Folder" }
foreach ($file in $files) 
{
    # this generates a relative URL like "SiteAssets/SitePages/SharePoint-Online-Now/95308-sharepoint.png"
    $relativeImagePath = $file["FileRef"].Replace($list.ParentWebUrl + "/", "")
    # add file to existing template.xml
    Add-PnPFileToProvisioningTemplate -SourceUrl $relativeImagePath -Path "template.xml"
}

Above code reads all file items from the Site Assets library and adds each and every file to the provisioning template. It will also create a new folder SiteAssets along the template file that contains all downloaded files.

Now when provisioning a new site those files will be uploaded and everything is fine.

Summing it up

By default files are not included in a PnP template file. However, you can use the Add-PnPFileToProvisioningTemplate cmdlet to download and add single files explicitly. Running this cmdlet for all files in a document library effectively adds the whole library to the template. When provisioning a new site from this template those files will be uploaded as well.

Comments