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. https://nikspatel.wordpress.com/2010/11/09/programmatically-configure-the-order-by-and-group-by-properties-of-the-sharepoint-lists-and-document-libraries-views/

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.


<# 
.DESCRIPTION 
    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"
 }

 [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

 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;
    $spView.Update();
   }
   
   # Update the list
   $spList.Update();
  }
  
  $spWeb.Dispose()
     }    
 
    $spSite.Dispose()
}

main

Advertisements
This entry was posted in SP2010 Dev PowerShell. Bookmark the permalink.