Quantcast
Viewing all articles
Browse latest Browse all 206

Updating list views from PowerShell

Recently I had to update a set of SharePoint list views. All of the views were the default “All Items” views of various lists, or views derived from this kind of view. That means, all of the views were ordered by the ID of the items.

My task was to create a solution for altering the “order by” field for these views to the Title field (or other arbitrary text fields). Since there are a lot of views and several environments (developer, test, production) for the alteration, I decided to create a PowerShell script to help the automation of the process. Originally I planned to use regular expressions for replacing the Name attribute of the FieldRef node, but finally I chose the XPath way. Here is the resulting function I used:

function updateView($list, $viewName, $orderByField)

  Write-Host "Updating ‘$viewName’ view of list ‘$list’ to be ordered by field ‘$orderByField’"
  $view = $list.Views[$viewName]
  [xml]$query = $view.Query
  $node = $query.selectSingleNode("//OrderBy/FieldRef")
  Write-Host // Original value was $node.GetAttribute("Name")
  $node.SetAttribute("Name", $orderByField)
  $view.Query = $query.OuterXml
  $view.Update()
  Write-Host Update finished.
}

And here is a sample for usage:

$site = Get-SPSite("http://MySharpointSite")
$web = $site.OpenWeb()
$list = $web.Lists["MyList"]
updateView $list "All Items" "Title"

Note, that this script is intended to update views having a well-formed CAML / XML value in the Query property, and a single “order by” field in that query. If you have no OrderBy node in the CAML query of your views, or have more than one, feel free to extend my solution.


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 206

Trending Articles