Office 365 - Deleting a Web Part using CSOM

I was recently assisting a customer to automate the creation and customization of their SharePoint Online sites using PowerShell, one of their requirements was to remove the "Get started with your site"Web Part from the landing page of each newly created Team Site.

The script below can be used to do this, please update the highlighted variables. This script can easily be adapted to remove a specific Web Part from other pages, simply update the highlighted values.

#Add references to SharePoint client assemblies and authenticate to Office 365 site
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$Username = ""
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Site = ""
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($Site)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username,$Password)
$Context.Credentials = $Creds

#Identify Web Parts on Home.aspx
$List = $Context.Web.Lists.GetByTitle("Site Pages")
$Pages = $List.RootFolder.Files
$Page = $List.RootFolder.Files | Where {$_.Name -eq "Home.aspx"}
$WPM = $Page.GetLimitedWebPartManager("Shared")
$WebParts = $WPM.WebParts

#Remove a Web Part - this removes the first Web Part registered on the page
$WebPart = $WebParts[0]
$Remove = $WebPart.DeleteWebPart()

...and it's gone!!!

Brendan Griffin - @brendankarl