Configure Order By and Group By Properties of the SharePoint Lists and Document Libraries Views using PowerShell

I have already blogged the code snippet about how to configure SharePoint lists and document library view’s group by settings programmatically.

Recently I came across the question where they wanted similar functionality using PowerShell. Here is the code snippet to configure the SharePoint list view group by settings using PowerShell. This PowerShell script takes site collection URL as a parameter, loads the SharePoint PowerShell Snapin, loops through all the sites, and updates the group by settings of the default view of “Shared Documents” library.

Please note that main entry point for this powershell script is “main” function and this function is invoked at the end of this script.

    Update the Document Library's default view group by settings

param (
   [string]$siteUrl = "$(Read-Host 'Enter the Site Collection URL. [e.g. "http://sp2010vm"])"

function main() {

 # check to ensure Microsoft.SharePoint.PowerShell is loaded
 $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
 if ($snapin -eq $null)
  Write-Host "Loading SharePoint Powershell Snapin"
  Add-PSSnapin "Microsoft.SharePoint.Powershell"


 ExecuteGroupByUpdate $siteUrl

function ExecuteGroupByUpdate([string]$siteUrl)
    $spSite = Get-SPSite $siteUrl
    $totalSPSites = "Total Sites: " + $spSite.AllWebs.Count
    Write-Host $spSite.url
    Write-Host $totalSPSites
 #Cycle through all sites in the collection
 foreach($spWeb in $spSite.AllWebs)
  Write-Host $spWeb.url -ForegroundColor Green    

  #Doc Library - Projects
  $docLibraryName = "Shared Documents";
  $viewQuery = " <GroupBy Collapse=""TRUE"" GroupLimit=""100""> <FieldRef Name=""Editor"" Ascending=""True""/> </GroupBy> <OrderBy> <FieldRef Name=""FileLeafRef"" /></OrderBy>";

  #Check if Doc Library Exists
  $isDocLibraryExists = "False"
  foreach($spList in $spWeb.Lists)
   if($spList.Title -eq $docLibraryName)
    $isDocLibraryExists = "True" 

  if($isDocLibraryExists -eq "True")
   $spList = $spWeb.GetList($spWeb.url + "/" + $docLibraryName)   
   Write-Host  "Document Library Name : " $spList.Title -ForegroundColor Yellow
   # Set the View Settings to the Group By Type
   if ($viewQuery -ne "")
    $spView = $spList.Views["All Documents"];
    $spView.Query = $viewQuery;
   # Update the list


This entry was posted in Uncategorized. Bookmark the permalink.