Instantly share code, notes, and snippets.

Embed
What would you like to do?
function Set-WebPart($fileName, $webPart, $ZoneId, $ZoneIndex, $listName, $isRootWeb) {
$web = Get-PnPWeb -Includes "ParentWeb"
#Destination page where the web part will be added
$serverRelativePageUrl = $web.ServerRelativeUrl + "/SitePages/" + $fileName
#Location for all web part XML-files
$directory = Get-Location
#web part file path
$file = $directory.Path + "\" + $webPart
#create new web part file path for updating information
$newFile = $file.Replace(".xml", "_new.xml")
#copy the file as temp for adding it to SharePoint page
Copy-Item -Path $file -Destination $newFile
#Replace the old ULR to new URL
if($isRootWeb) {
#Replace URL for the rootsite
$rootWeb = $web.ParentWeb
(Get-Content $newFile) -replace '/dbag/dmses', $rootWeb.ServerRelativeUrl | Set-Content $newFile
}
else {
#Replace the URL for the subiste
(Get-Content $newFile) -replace '/dbag/dmses/provtempl', $web.ServerRelativeUrl | Set-Content $newFile
}
#Check if the web part uses list
if($listName) {
$list = Get-PnPList -Identity $listName
$views = Get-PnPView -List $listName
#Replace the known old list ID with the new of the destination subsite
Write-Host(" Replace list id with " + $list.Id)
(Get-Content $newFile) -replace '{#listNameId#}', $list.Id | Set-Content $newFile
#Replace the known old view ID with the new view ID of the destination subiste
Write-Host(" Replace view id with " + $views[0].Id)
(Get-Content $newFile) -replace '{#viewNameId#}', $views[0].Id | Set-Content $newFile
}
#Add web part to SharePoint page
if($webPart -ne "provisioningtemplate_webpart_Homepage.aspx_3.xml") {
Add-PnPWebPartToWebPartPage -ServerRelativePageUrl $serverRelativePageUrl -Path $newFile -ZoneId $ZoneId -ZoneIndex $ZoneIndex
} else {
#Bug German Calender View Part for using Add-PnPWebPartToWebPartPage
#Solution: Use default SharePoint CSOM
Add-WebPartToPage -ServerRelativePageUrl $serverRelativePageUrl -newFile $newFile -wpZoneID $ZoneId -wpZoneOrder $ZoneIndex
}
Remove-Item -Path $newFile
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment