Sunday, April 20, 2014

Programmatically display all items in SharePoint document library as a flat list without folders

Let’s assume that we have a document library with a deep folder structure. Sometimes it’s very hard and time consuming to locate documents under those folders.

image

Is there a way to display all files as a flat list without folders? It’s very simple, we only need to do some modifications to the view

image

If we have to automate the behavior, we can use either C# or PowerShell to do the needful. In both cases we need to update SPView.Scope property.

C# 

  1. var viewCollection = newDocLib.Views;
  2. const string viewName = "File List";
  3. var viewFields = new StringCollection
  4.          { "Type", "LinkFilename", "Modified", "Editor" };
  5. var filesOnlyView = viewCollection.Add(viewName, viewFields, string.Empty, 5, true, false);
  6. filesOnlyView.Scope = SPViewScope.Recursive;
  7. filesOnlyView.Update();
  8. newDocLib.Update();

PowerShell

Following script will create the view for all document libraries in all site collections within a specific web application

  1. Get-SPSite -WebApplication "http://sp13:8080" -limit All | ForEach-Object {  
  2. foreach ($w in $_.AllWebs){
  3. foreach($docLib in $w.Lists | where {$_.BaseTemplate -eq "DocumentLibrary"})
  4.   {
  5.     #create list view
  6.     $viewCollection = $docLib.Views
  7.     $viewName = "File List"
  8.     $fields = $docLib.Views["All Documents"].ViewFields.ToStringCollection()
  9.     $itemOnlyView = $docLib.Views.Add($viewName, $fields,"", 30, $True, $False)
  10.     $itemOnlyView.Scope = "Recursive"
  11.     $itemOnlyView.Update()
  12.     $docLib.Update()        
  13.   }
  14. }
  15. }

This will create a new view called “File List” which displays all files in the library without folders

image

No comments: