Daily Archives: August 18, 2018

Update Webpart view in a Page programmatically using PowerShell

For a SharePoint Administrator managing the changes in the view for a webpart is a very tiresome job. If a single view changes in the library or list then a page which uses the webpart view has to be manually changed. To change the view in the webpart the administrator has to edit the page, modify webpart and save the page. Imagine if you have 5 pages and each page have 5 webparts and a view is changed. You have to open each page in edit mode and the each webpart edit, change view and save one by one.

To effectively change the webpart view in a page, CSOM have an api to get the webpart in a page as a XML. Manipulate the XML and get the webpart name and view name from xml. Usually when a webpart is added to the page the view xml is cached to the page. So when the view is changed in the library / list the updated view will not be reflected in the page. The PowerShell code will get the webpart and update the view xml

The full code is here you can download

#### To change the webpart view
#### Get the webpart from the page. get the WebPart XmlDef and find the View ID
### List has hidden view for the web part added. So get the view from the List and change that view.
### Its all about that hidden View

Add-Type -Path ".\CSOM\Microsoft.SharePoint.Client.dll"
Add-Type -Path ".\CSOM\Microsoft.SharePoint.Client.Runtime.dll"

$now=Get-Date -format "dd-MMM-yy,HH:mm:ss"
$fileFormat = Get-Date -format "dd-MMM-yy_HHmmss"
Write-Host "Script Start : '$($now)'" -ForegroundColor Yellow

$username = ""
$password = ""
$srcUrl = "" # full url like hhtp://my.sharepoint.com/
$sitePath = "/SitePages/"
$srcLibrary = "Documents"
$pagesList = @("Home.aspx") # you can specify many pages to be changed array here
$wepPartChangeList = @{"Documents" = "All Documents" ; } ### dictionary value Key = Web part Title seen on page, Value = View Name from the Library

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)

Write-Host "Authenticating ..." -ForegroundColor White
$srcContext = New-Object Microsoft.SharePoint.Client.ClientContext($srcUrl)
$srcContext.Credentials = $credentials
$srcWeb = $srcContext.Web
$srcList = $srcWeb.Lists.GetByTitle($srcLibrary)


    Write-Host $_.Exception.Message -ForegroundColor Red
Write-Host "Connected to the web..." -ForegroundColor Green

foreach($page in $pagesList)
    $filePath = $sitePath + $page
    $pageObject = $srcWeb.GetFileByServerRelativeUrl($filePath)
    $WPM = $pageObject.GetLimitedWebPartManager("Shared")

    $webParts = $WPM.WebParts

    foreach($wp in $webParts)

        if( $wepPartChangeList[$wp.WebPart.Title] -ne $null)
        #if($wp.WebPart.Title.IndexOf("Documents") -gt 0)
            Write-Host "---------- Processing Page  = $($pageObject.Name) Webpart = $($wp.WebPart.Title) ------- " -ForegroundColor Yellow

            $wpXmlContent = $wp.WebPart.Properties["XmlDefinition"]
            $wpXml = New-Object -TypeName XML
            $viewGUID = $wpXml.View.Name

            $viewName = $null
            $viewName = $wepPartChangeList[$wp.WebPart.Title]
                $view = $srcList.Views.GetByTitle($viewName)
                $wpView = $srcList.Views.GetById($viewGUID)
                #$viewXml = New-Object -TypeName XML
                write-host "### WebPart Xml -------Before Xml Change -----" -foreground cyan
                write-host "$($wpView.ListViewXml)"              

                $wpViewFields = $wpView.ViewFields
                $viewFields = $view.ViewFields

                foreach($vField in $viewFields)

                $wpView.RowLimit = $view.RowLimit
                $wpView.ViewQuery = $view.ViewQuery
                write-host "### WebPart Xml -------After Xml Change -----" -foreground cyan
                write-host "$($wpView.ListViewXml)"
                write-host "*******************************************************************" -foreground cyan
                Write-Host "Unable to fing view for " $wp.WebPart.Title -ForegroundColor Cyan

    #Write-Host "Next Page " 


$now=Get-Date -format "dd-MMM-yy,HH:mm:ss"
Write-Host "END : '$($now)'" -ForegroundColor Yellow<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>


Set SharePoint folder level permission using C# & PowerShell

The PowerShell script here will set the permission to the folder inside the document library. The PowerShell script uses the C# code for permission. The C# code will add mandatory Full Control access and break the inheritance. The code uses the lambda function to find the unique permission. Since PowerShell natively does not support lambda expression the C# code is embedded within the PowerShell

The full script is below

$cSharp = @”

using System;

using System.Security;

using System.Linq;

using System.Collections.Generic;

using Microsoft.SharePoint.Client;

namespace SPClient


public class Permission


private static string username = “”;

private static string password = “”;

private static string srcUrl = “”;

private static string[] groupNames = { “Team Site Members” };

private static string srcFolder = “folder path(/sites/dev/shared documents/folder1)”;

private static string permissionType = “Edit”;

private static string mandatoryGroupName = “Developer Owners”;

public static void ApplyPermission()




var securePassword = new SecureString();

foreach (char c in password)




using (var clientContext = new ClientContext(srcUrl))


Console.WriteLine(“Authenticating…” + srcUrl);

clientContext.Credentials = new SharePointOnlineCredentials(username, securePassword);

Web srcWeb = clientContext.Web;

Folder applyFolder = srcWeb.GetFolderByServerRelativeUrl(srcFolder);





Console.WriteLine(“Applying to folder : ” + srcFolder);

GroupCollection groups = srcWeb.SiteGroups;



var myGroups = (from a in groupNames

from w in groups

where a == (w.Title)

select w).ToArray();


var coordinator = (from a in groups where a.Title == mandatoryGroupName select a).FirstOrDefault();

RoleDefinitionCollection rdc = srcWeb.RoleDefinitions;

RoleDefinition myRole = rdc.GetByName(permissionType);

RoleDefinition coordinateRole = rdc.GetByName(“Full Control”);





Console.WriteLine(“Role definitions…”);

if (!applyFolder.ListItemAllFields.HasUniqueRoleAssignments)


Console.WriteLine(“Breaking inheritance…”);

applyFolder.ListItemAllFields.BreakRoleInheritance(true, false);




Console.WriteLine(“Inheritance broken already…”);


var folderRoles = applyFolder.ListItemAllFields.RoleAssignments;

Console.WriteLine(“Applying the role assignments …”);

RoleDefinitionBindingCollection coordinateRdb = new RoleDefinitionBindingCollection(clientContext);


RoleDefinitionBindingCollection collRdb = new RoleDefinitionBindingCollection(clientContext);




folderRoles.Add(coordinator, coordinateRdb);

foreach (Group eachGroup in myGroups)


Console.WriteLine(“Applying Group: ” + eachGroup.Title);

folderRoles.Add(eachGroup, collRdb);




Console.WriteLine(“Successfully applied”);




catch(Exception ex)









$assemblies = @(





Add-Type -TypeDefinition $cSharp -ReferencedAssemblies $assemblies