Views

Creating List and Library Views in SharePoint with PowerShell

The code snippet below illustrates the creation of a view on a list. I generally leave the “All Items” views alone, and create new views to do anything specific for an application within SharePoint – it just makes life easier in the long run.

# Connect to SharePoint
$web = get-spweb "https://server/sites/site_collection/subsite"

# get the list to make a view
$list = $web.Lists["My List"]

$view_name = "My View"

# If the view already exists, remove it
if ($list.Views[$view_name] -ne $null){
    $view = $list.Views[$view_name]
    $list.Views.Delete($view.Id) > $null
    $list.Update() > $null
    $web.Update() > $null
}

# Create the view
$view_fields = New-Object System.Collections.Specialized.StringCollection
$view_fields.Add('LinkTitle') > $null
$view_fields.Add('Created') > $null
$view_fields.Add('Modified') > $null
$view_query = "<OrderBy><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>"
$view_row_limit = 50
$view_paged = $true
$view_default = $true
$new_view = $list.Views.Add($view_name, $view_fields, $view_query, $view_row_limit, $view_paged, $view_default)

# Release Resources
$web.Close()
$web.Dispose()

Note that if you try to remove the only view existing on a list or library, it will fail – there must always be at least one view. Also note that fields must be identified by their internal names. Oh – finally – the view query is expressed in CAML – you can look that up elsewhere (it’s a special kind of hell).

Posted by Jonathan Beckett in Notes, 0 comments