Add, Remove, And Get All Web Parts From Modern Site Page Using PnP PowerShell

In this blog, we are going to retrieve all the webparts present in a modern site page. Also, we will see how to add different web parts and delete a web part from a modern site page using PnP PowerShell.

First, we need to connect to the site. To perform the connection, add the following lines.

$siteURL = Read-Host “Provide site url”  

Connect-PnPOnline -Url $siteURL  

#Executing this line will ask for credentials. Provide use name and password to connect. 

$page=Get-PnPClientSidePage Identity “ModernWebPage.aspx” #Get the page on which you are going to perform add and remove web parts.  

Add different Webparts

To add a text editor web part,

Add-PnPClientSideText -Page $page -Text “Welcomes To SharePoint”  

To add a list view web part,

Add-PnPClientSideWebPart -Page $page -DefaultWebPartType “List” -WebPartProperties @{selectedListId=”609f95e4-7022-417d-a57f-693673f7eff9″}  

You can see two web parts are added successfully in the modern site page. 

Retrieve all web parts used in the modern site pages.

$webParts = $page.Controls  

#if there are more than one webparts  

foreach($webpart in $webparts) {  

    Write – Host “WebPart Id ”  

    $webpart.InstanceId  

    Write – Host “Title ”  

    $webpart.Title  

}  

Remove a webpart

Remove-PnPClientSideComponent -Page $page -InstanceId 0c6a1475-c5e8-414e-9e6d-c90c3b5c01b7   

To remove web parts, we need to provide web part instance id that we have already got in PowerShell window output while retrieving the web parts. After executing the above command, it will open a dialog box to confirm web part delete. Click on “yes” to delete the web part.

$siteURL = Read – Host “Please provide site url”  

try {  

    Connect – PnPOnline – Url $siteURL  

    $page = Get – PnPClientSidePage – Identity “ModernWebPage.aspx”  

    #Add webparts in modern page  

    Add – PnPClientSideText – Page $page – Text “Welcomes To SharePoint” – Section 2 – Column 1  

    Add – PnPClientSideWebPart – Page $page – DefaultWebPartType“ List” – Section 2 – Column 1 – WebPartProperties @ {  

        selectedListId = “609f95e4-7022-417d-a57f-693673f7eff9”  

    }  

    #Retrieve webparts from modern page  

    $webParts = $page.Controls  

    foreach($webpart in $webparts) {  

        Write – Host “WebPart Id ”  

        $webpart.InstanceId  

        Write – Host “Title ”  

        $webpart.Title  

    }  

    #Remove webparts from modern page  

    Remove – PnPClientSideComponent – Page $page – InstanceId 0 c6a1475 – c5e8 – 414e-9 e6d – c90c3b5c01b7  

} catch {  

    Write – Host – ForegroundColor Red ‘Error ‘, ‘:’  

    $Error[0].ToString();  

    sleep 10  

Tags: , , ,

Leave a Reply

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