Second Life of a Hungarian SharePoint Geek

May 25, 2013

Updating list views from PowerShell

Filed under: PowerShell, SP 2010, Views — Tags: , , — Peter Holpar @ 08:22

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.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: