[转]Use PowerShell to Manage Lists, Views, and Items in SharePoint(使用PowerShell管理列表、视图、列表项)
Creating Lists in SharePoint 2010
One of the most powerful features of SharePoint from an end user’s perspective is the ease of creating and customizing lists, views, and items. Lists store data. SharePoint 2010 includes a large number of list templates that can be used as they are or as a starting point to tailor them to fulfill your specific business requirements. Lists have a set of configurable settings that apply to all lists, as well as custom settings that apply only to the specific type of list used.
Let’s take a look at the templates available. We can do this using the ListTemplates property on an object of the type SPWeb. First, we store an object of the type SPWeb in a variable:
PS > $spWeb = Get-SPWeb -Identity http://SPServer
Next, we use the ListTemplates property and select the name and description, as shown in the following image.
We can use a template when creating a new list (of course we’ll do this by using Windows PowerShell). When creating a list in SharePoint 2010, you use the Add method of theSPListCollection class. This method has seven overloads (method signatures, or ways in which the method can be called). The one we will be using for our example accepts three parameters: the list title, description, and template type to be used. The title and description parameters are both of the type System.String, and the template parameter is of the type SPListTemplateType, so we need to provide an instance of this type as a value for this parameter.
Here, we create a variable containing the Contacts list template type, which we obtain from the Microsoft.SharePoint.SPListTemplateType enumeration:
PS > $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::Contacts
PS > $spListCollection = $spWeb.Lists
PS > $spListCollection.Add("My Contacts","Description",$listTemplate)
Why do we need this intermediary spListCollection variable? Why not call the Add method directly with $spWeb.Lists.Add? If we used the Add method directly and repeated the command ten times, the metadata for all available lists in the site would be loaded ten times. Storing the lists collection in a variable and working with that variable minimizes the amount of memory consumed, because the lists are loaded only once.
Modifying Lists in SharePoint 2010
Let’s see how we can modify our new list. First, we get the list using the GetLists() method and store it in a variable:
PS > $spList = $spWeb.GetList("/Lists/My Contacts")
With the list stored in a variable, we can go ahead and set all kinds of cool stuff. Here’s how to add a list to the Quick Launch:
PS > $spList.OnQuickLaunch = "True"
PS > $spList.Update()
When you run the command above, the list appears on the Quick Launch. Setting the value to False hides the list from the Quick Launch. If we want to change the list’s description, we can simply use the Description property:
PS > $spList.Description = "My Contact List"
PS > $spList.Update()
Adding List Fields
It’s also possible to add additional fields to a list. To create a field in a SharePoint 2010 list, use the Add method provided by the SPFieldCollection class. Here, we create a simpleText type field in a SharePoint list:
PS > $spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
PS > $spList.Fields.Add("TextField",$spFieldType,$false)
In this example, we create an SPFieldType object with the value Text and store it in the variable spFieldType. We then use the Add method and pass in the field’s display name, followed by the variable spFieldType, followed by Boolean False. The last parameter in this overload of the Add method specifies whether the new field is required to always contain a value. Our example creates a new text field in the list with the display name of TextField that will not require any input. An additional Boolean parameter you can use with the Add method compacts the field name to eight characters, if set to True.
SharePoint 2010 supports other types of fields as well. Adding a Choice field is a little different since it requires additional information regarding the possible choices. You can store the choices in an instance of the System.Collections.Specialized.StringCollection class, as shown in this example:
PS > $choices = New-Object System.Collections.Specialized.StringCollection
PS > $choices.Add("First Choice")
PS > $choices.Add("Second Choice")
PS > $choices.Add("Third Choice")
Now that we have our choices stored in a variable, we can use the variable when creating a Choice type field:
PS > $spFieldType = [Microsoft.SharePoint.SPFieldType]::Choice
PS > $spList.Fields.Add("ChoiceField",$spFieldType,$false,$false,$choices)
We use the choices variable to associate a list of options with the field.
Managing List Views
Let’s move on and look at how to manage list views in SharePoint 2010. Views enable you to create customized representations of list data for specific purposes, such as displaying specific fields. When a new list in SharePoint is created, a default view is added. Document Library lists get the All Documents view, Picture Library lists get the All Pictures view, and most of the other list types get the All Items view.
Before we can edit an existing view in SharePoint 2010, we need to retrieve it. We can use the GetViewFromUrl method of the SPWeb class. Let’s get the Contacts list we created earlier:
PS > $spView = $spWeb.GetViewFromUrl("/Lists/My Contacts/AllItems.aspx")
When new fields are created, they are not added to a view by default. We can, of course, add a field to a view by using Windows PowerShell. First, we need to create a reference to the field that we want to add to the view:
PS > $spField = $spList.Fields["TextField"]
We then can use the Add method provided by the SPViewFieldCollection class to add the field to a view and finally use the Update() method to set the changes:
PS > $spView.ViewFields.Add($spField)
PS > $spView.Update()
You can do a lot more cool stuff with views such as set custom queries, create new views, and remove views.
Managing List Items
Let’s move ahead and take a look at how to add list items to a list. The SPList class provides the AddItem method, which is used to create new list items. When you call theAddItem method, an object of the type Microsoft.SharePoint.SPListItem is returned. Because we want to populate the properties of the new list item, we need to store the object in a variable in order to continue to work with it:
PS > $spListItem = $spList.AddItem()
Now we can start assigning values to the different fields the corresponding list item inherits from the parent list. The SPListItem class provides a parameterized Item property for accessing the value contained in a particular field. To specify the value of the Title field, we can use the following:
PS > $spListItem["Title"] = "New Item"
We can assign additional values to fields as well. In the next example, we add values to the TextField and ChoiceField, which we created earlier in this example:
PS > $spListItem["TextField"] = "Hey hey"
PS > $spListItem["ChoiceField"] = "First Choice"
Finally, we use the Update() method to create the new list item:
PS > $spListItem.Update()
What if we want to update an existing list item? Well, the SPList class provides a few methods we can use to retrieve a specific from a list. The most common methods areGetItemById() and GetItems().
Wait a minute! Isn’t it simpler to loop through the Items collection and create a filter using the Where-Object cmdlet? It is simpler and does feel like the Windows PowerShell way of doing things, but consider this: When you use the Items property on an SPList object, all the list items in the list are read into memory, meaning that large lists may consume a lot of memory. A better approach is to use either the GetItemsById() method or the GetItems() method to minimize memory consumption.
The GetItemById() method requires that we know the ID of the particular item. In many cases, we have no idea of an item’s ID, but we might know the item’s title or some other value. This is where the GetItems() method becomes useful. The method returns all list items or a subset of list items as defined by search criteria in a CAML query.
To use a CAML query with the GetItems method, we first need to create an object of the type Microsoft.SharePoint.SPQuery:
PS > $spQuery = New-Object Microsoft.SharePoint.SPQuery
The SPQuery object supports the Query property, which we use to place a CAML query. Here’s the CAML query we’ll use in our example:
PS > $camlQuery =
>> ‘<Where><Eq><FieldRef Name="Title" /><Value Type="Text">True</Value></Eq></Where>'
We create a new query containing a Where statement using the <Where> tag. Next, we specify an equals expression using the <Eq> tag. For other types of searches, you can replace this tag with the appropriate one, such as <Lt> or <Gt> to search for list items where the value of this field is less than or greater than a value, respectively.
We then specify the field we want to query against using the <FieldRef> tag. In this example, we want to look at the Title field in the list. Finally, we use the <Value> tag to specify that the value type is Text and that the value should equal New Item.
After we have created a CAML query and stored it in a variable, we assign it to the Query property of our SPQuery object:
PS > $spQuery.Query = $camlQuery
Before using the SPQuery with the GetItems method, we should specify the RowLimit property that is used to limit the amount of items returned per page. If we run the SPQuerywithout setting the row limit, the query will select all items matching the criteria and might fail on lists with a large number of items:
PS > $spQuery.RowLimit = 100
Here, we set the RowLimit property to 100 so that only 100 list items are returned per page. The RowLimit value should be between 1 and 2000. Finally, we can call theGetItems() method with the SPQuery object instance we created earlier for input:
PS > $spListItem = $spList.GetItems($spQuery)
Now it’s a simple task to update the list item. In the example below, we change the item’s Title. Note that the GetItems() method returns a ListItemCollection, so even if only one value is returned, we still have to index the first element or use the ForEach-Object cmdlet to loop through each item:
PS > $spListItemCollection | ForEach-Object {
>> $_["Title"] = "New Value"; $_.Update()
>>}
Summary
In this post, we’ve looked at how to manage lists, views, and items by using Windows PowerShell. We saw examples about how to create new lists, modify list properties, add fields, manage views, and how to work with items. Chapter 14 in PowerShell for SharePoint 2010 Administrators (available October 2010) takes list and view management one step further by showing how to manage lookup fields, how to retrieve lists using a simple function, how to automate list creation, and much more. In Chapter 15, you’ll see detailed examples about how to create, manage, delete, and copy list Items.
NG, that is all there is to managing lists, views, and items by using Windows PowerShell and SharePoint. Guest Blogger Week with Niklas Goude and SharePoint will continue tomorrow.
We would love for you to follow us on Twitter and Facebook. If you have any questions, send email to us at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.