Powershell Script To Create Modern SharePoint Page With Different Page

Introduction

 
SharePoint Modern Pages has picked up the pace because of its modern UI and multiple web parts that are content creator friendly.
 
Because of this, there could be a scenario where we would need to create multiple pages. Creating this manually can be a difficult task. A better approach would be to create a PowerShell script which would help with this task. 
 
PnP PowerShell can help us create Modern SharePoint Pages with one single command.

We can even create pages with different page layouts.
 
So we will create two scripts;  one which can create pages with different page layouts and once which can create pages from Templates.
 
Step 1 - Install PnP PowerShell
 
To install PnP PowerShell if not already installed please use the below command.
 
Install-Module SharePointPnPPowerShellOnline -Scope CurrentUser
 
Step 2 - Create a CSV File
 
We can create a csv file with columns such as pageName, layoutName (layoutName can be Article, Home, RepostPage, SingleWebPartAppPage, Space)
 
To download the sample CSV file check the source code zip which contains CSV along with the PowerShell Script. We can even provide folders in the PageName section, for example (e.g. /temp/Test 1) where "temp" is the folder name. If it's not found the library it would create a folder and "Test 1" is the page name.  PowerShell Script Code will  import CSV file and create Modern Pages based on the input.
 
Step 3 - PowerShell Script
  • The below script will create a Modern Page with different layout as input in the CSV file.

    Please change the CSV file with the file name and the path where the CSV file is stored.
    1. $siteCollectionURL = Read - Host "Please enter your site collection URL"  
    2. $credentials = (Get - Credential)  
    3. Connect - PnPOnline– Url $siteCollectionURL– Credentials $credentials  
    4. $csvInput = Import - Csv createModernPage.csv  
    5. foreach($input in $csvInput) {  
    6.     Add - PnPClientSidePage - Name $input.pageName - LayoutType $input.layoutName  
    7. }  
  • The below script will create a Modern Page from a template
    1. $siteCollectionURL = Read - Host "Please enter your site collection URL"  
    2. $templateName = Read - Host "Please enter template Name"  
    3. $credentials = (Get - Credential)  
    4. Connect - PnPOnline - Url $siteCollectionURL– Credentials $credentials  
    5. $csvInput = Import - Csv createModernPage.csv  
    6. $finalTemplateName = "Templates/" + $templateName  
    7. $template = Get - PnPClientSidePage - Identity $finalTemplateName  
    8. foreach($input in $csvInput) {  
    9.     $fullFileName = $input.pageName + '.aspx'  
    10.     $template.Save($fullFileName)  
    11. }  

Conclusion


This can be very helpful for automating the modern page creation process from CSV. We can even extend this script as per our needs.