Play with SharePoint 2010 List using PowerShell
February 22, 2012 4 Comments
In this post, we will learn how to do basic operations on SharePoint list using PowerShell.
Lets start with List creation
$spAssigment = Start-SPAssignment #Use to dispose SPWeb safely $spWeb = Get-SPWeb ServerURL -AssignmentCollection $spAssignment #Get SPWeb Instance $spWeb.ListTemplates | Select Name, Description #Display List of Templates Available $spTemplate = $spWeb.ListTemplates["Custom List"] #Create SPTemplate instance of Type Custom List $spWeb.Lists.Add("List Title", "Description", $spTemplate) #Add list to site
Add list to quick launch and fields to list
$spList = $spWeb.Lists["List Title"] #Get list instance $spList.OnQuickLaunch = $True #Set true to display in Quick Launch $spList.Update() #Update list to reflect changes in site $spFieldType = [Microsoft.SharePoint.SPFieldType]::Text #Get Field type to create $spList.Fields.Add("My Column", $spFieldType, $false) #Add new field to list
Create View and set fields for view
$spViewQuery = “<OrderBy><FieldRef Name=”"Modified”" Ascending=”"False”" /></OrderBy>” $spViewFields = New-Object System.Collections.Specialized.StringCollection #Create string collection object $spViewFields.Add("Title") #Add columns $spViewFields.Add("My Column") $spViewName = "My View" #Set view name $spListView = $spList.Views.Add($spViewName, $spViewFields, $spViewQuery, 100, $True, $False, “HTML”, $False) #Add view to list $spListView.DefaultView = $True #Set view as default $spListView.Update() #Update view to reflect changes in site
Add few List Items
$spListItem = $spList.Items.Add() #Add new list item object $spListItem["Title"] = "First Item" #Set field value $spListItem["My Column"] = "My Text for first item" $spListItem.Update() #Update list item object to reflect changes in site $spListItem = $spList.Items.Add() $spListItem["Title"] = "Second Item" $spListItem["My Column"] = "My Text for second item" $spListItem.Update()
Update List Items
$spListItems = $spList.Items #Get list item collection $spListItemsCount = $spListItems.Count #Get list items total count for($Counter = $spListItemsCount-1; $Counter -ge 0; $Counter--) { $spListItem = $spListItems[$Counter] #Get list item via index $spListItem["Title"] = "Updated Title" + $Counter $spListItem["My Column"] = "My Column" + $Counter $spListItem.Update() }
Delete List Items
for($Counter = $spListItemsCount-1; $Counter -ge 0; $Counter--) { $spList.Items[$Counter].Delete() #Delete list item }
Delete List
$spList.Delete()
Finally Dispose web object
Stop-SPAssignment $spAssignment