February 15, 2017

SharePoint: Batch update CSWP query using PowerShell

Task

Needed to update CSWP query on a lots of sites programmatically. URL of the content was changed so needed to change the Path rule in CSWP.

Solution

Script below recursively uses Office PnP PowerShell, so first install it using

Install-Module SharePointPnPPowerShellOnline -AllowClobber

Script goes through all subsites, publishing pages on the subsites, and web parts on the publishing pages and updates the path search rule, but obviously you can just modify the first two parameters to make any change you wish.

NOTE! It determines if web part is CSWP by looking at the DataProviderJSON property of the web part.

Flip $saveChanges to $true to actually persist changes.

$stringToFind = @('path:\"https://xyz.sharepoint.com/oldsite/')
$stringToReplace = @('path:\"https://xyz.sharepoint.com/newsite/')
$saveChanges = $false
$credentials = Get-Credential

function UpdateSearchWebParts($webUrl)
{
    Connect-PnPOnline -Url $webUrl -Credentials $credentials

    Write-Host "Updating CSWP source string:"$stringToFind " with Target string " $stringToReplace
   
    foreach($subweb in Get-PnPSubWebs -Recurse)
    {
        Write-Host "Subweb '$($subweb.Title)'"
       
        # Get pages
        foreach($page in Get-PnPListItem -Web $subweb -List "pages" -Fields "FileRef" | Where { $_.FieldValues.FSObjType -eq 0})
        {  
            Write-Host "Page '$($page["FileRef"])'"
         
            if($saveChanges) {
                Set-PnPFileCheckedOut -Url $page["FileRef"] -Web $subweb
            }
           
            #Get CSWP
            $webparts = Get-PnPWebPart -Web $subweb -ServerRelativePageUrl $page["FileRef"]
            foreach($webpart in $webparts)
            {
                if($webpart.WebPart.Properties.FieldValues.DataProviderJSON -eq $null -or !$webpart.WebPart.Properties.FieldValues.DataProviderJSON.Contains($stringToFind))
                {
                    continue
                }

                Write-Host "Web part: " $webpart.WebPart.Title               
               
                Write-Host "Old: '"$webpart.WebPart.Properties.FieldValues.DataProviderJSON"'"
                $newJson = $webpart.WebPart.Properties.FieldValues.DataProviderJSON.Replace($stringToFind, $stringToReplace)
                Write-Host "New: '"$newJson"'"

                if($saveChanges) {
                    Set-PnPWebPartProperty -ServerRelativePageUrl $page["FileRef"] -Identity $webpart.Id -Key DataProviderJSON -Value $newJson
                }
            }

            if($saveChanges) {
                Set-PnPFileCheckedIn -Url $page["FileRef"] -Web $subweb -CheckinType MajorCheckIn
            }           
        }       
    }
}

UpdateSearchWebParts https://xyz.sharepoint.com

No comments:

Post a Comment