Automating SharePoint 2010 list view configuration

SharePoint list views are one of the key components using which users will interact with your lists as they use the site.
Quite often, when new organizational policy kicks in – you may be asked to modify lists on your site to facilitate additional fields or restrictions your business users want to enforce on their lists.
More often than not – list changes requested by business users involve in fact changes to list views. For example, a query on your list view to filter out items by certain field.
Let’s take a look at how such change can be automated on one list so you can automate it anywhere else on the site and all of the sites you need.

I assume you’re running fully configured SharePoint test environment; for this example you will need SharePoint 2010 Foundation; although if you have SharePoint 2010 Server – all the better :)

1. Open SharePoint 2010 Management Shell.
2. Execute the following set of commands:


$SPSite = Get-SPSite | Where-Object {$_.Url -eq "http://intranet.contoso.com"}
$RootWeb = $SPSite.RootWeb
$NewListTemplate = $RootWeb.ListTemplates["Announcements"]
$NewListInstance = $RootWeb.Lists.Add("Announcements List", "Announcements List",
$NewListTemplate)
$SPList = $RootWeb.Lists[$NewListInstance]
$SPList.OnQuickLaunch = $true
$SPList.Update()

$ListView = $SPList.DefaultView;
$ListFields = $SPList.Fields;
$ListViewFields = $ListView.ViewFields;
$ListViewFields.Add($ListFields["Expires"]);
$ListView.Query = ""
$SPList.Update()

$SPListItem = $SPList.Items.Add()
$SPListItem["Title"] = "New Announcement 1"
$SPListItem["Expires"] = [System.DateTime]::Now
$SPListItem.Update()

$SPListItem = $SPList.Items.Add()
$SPListItem["Title"] = "New Announcement 2"
$SPListItem["Expires"] = [System.DateTime]::Parse("1/1/2012")
$SPListItem.Update()

Above, first we create a new announcements list. This list is next used to modify the default view on.
The default view will be given a new filter query where only the items with the expiry date greater than today will be displayed.
The expiry date is the default metadata field for the announcement lists; however, you have to add the field to the list view first since the Expiry date is not the default field on the view.
Once added, the field will participate on our new filtering query.
Lastly, we add two test items, one with the today’s expiry date and another with a future date.
When you execute the query above and access the list – you will only see the item with the future Expiry date in the list. Which proves our filtering has been applied.
Enjoy!

This entry was posted in sharepoint 2010 and tagged , , , . Bookmark the permalink.

Comments are closed.