共用方式為


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")
$Context.Load($List)
$Context.ExecuteQuery()
$Pages = $List.RootFolder.Files
$Context.Load($Pages)
$Context.ExecuteQuery()
$Page = $List.RootFolder.Files | Where {$_.Name -eq "Home.aspx"}
$Context.Load($Page)
$Context.ExecuteQuery()
$WPM = $Page.GetLimitedWebPartManager("Shared")
$Context.Load($WPM)
$Context.ExecuteQuery()
$WebParts = $WPM.WebParts
$Context.Load($WebParts)
$Context.ExecuteQuery()

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

...and it's gone!!!

Brendan Griffin - @brendankarl

Comments

  • Anonymous
    September 08, 2015
    great stuff man!
  • Anonymous
    October 04, 2016
    Good one ! A minor change $webpart = $WebParts[0]$Context.Load($webpart)$webpart.DeleteWebPart()$Context.ExecuteQuery()No Need to call executequery method twice ! and adding $context.Dispose() is a best practice!