30+ pages, all with webparts, and one webpart on all pages had to be changed. Someone within the organisation starts clicking and after two days he was ready. Then the same question came for the same webpart to change it back again, so he starts clicking again. And a few weeks later, could we…. ?

And I thought this is going to happen more often during the implementation period, there must be an easier way.

I thought, if I configure the webpart ones, export the webpartfile and find a way to import it with PowerShell.

And yes, PowerShell rocks ?!


clear

$user = "?????????????"
$password = ConvertTo-SecureString "?????????????" -AsPlainText -Force
$credentials = New-Object –TypeName "System.Management.Automation.PSCredential" –ArgumentList $user, $password

$siteURL = "https://tenant/sites/site/subsite"

Connect-PnPOnline -Url $siteURL -Credentials $credentials
$ctx = Get-PNPContext

Write-Host "Connected to:" $siteURL -ForegroundColor Green

#------

$folderUrl = "/SitePages"
$folder = Get-PnPFolder -Url $folderUrl

$ctx.Load($folder.Files)
$ctx.ExecuteQuery()

foreach($file in $folder.Files){

  $serverRelativePageUrl = "/SitePages/" + $file.Name

  $webparts = Get-PNPWebPart -ServerRelativePageUrl $serverRelativePageUrl

  foreach($webpart in $webparts){

    if($webpart.WebPart.Title -eq "MyWebPart") {

      Write-Host "Page:" $file.Name -ForegroundColor Yellow
      Write-Host "- Url:" $serverRelativePageUrl

      Write-Host "- Deleting Webpart: " $webpart.WebPart.Title ($webpart.Id) -ForegroundColor Red
      Remove-PNPWebPart -ServerRelativePageUrl $serverRelativePageUrl -Identity $webpart.Id

      Write-Host "- Adding Webpart: MyWebPart.webpart"
      Add-PNPWebPartToWebPartPage -ServerRelativePageUrl $serverRelativePageUrl -Path "C:\_Data\MyWebPart.webpart" -ZoneId "LeftColumn" -ZoneIndex 0
    }
  }

}

 

Leave a Reply

Your email address will not be published.