Wednesday, 27 June 2012

Add,Update,Delete List items using powershell sharepoint 2010

A simple example of a powershell script to Add, Update, Delete items in a list in SharePoint 2010.

Add List Item:

$spAssignment = Start-SPAssignment
$mylist = (Get-SPWeb -identity http://SP -AssignmentCollection $spAssignment).Lists["listName"]
$newItem = $mylist .Items.Add()
$newItem["Title"] = “Added by Powershell”
$newItem["description"] = “My PowerShell Magic”
$newItem.Update()
Stop-SPAssignment $spAssignment

In the example we use the Start-SPAssignment and Stop-SPAssignment cmdlets to make sure that the objects are disposed correctly. Also note that we assign Get-SPWeb to the assignment. We then use the Add() method to create a new item in SharePoint 2010.

Update List Item:

$SPAssignment = Start-SPAssignment
$SPWeb = Get-SPWeb http://SP -AssignmentCollection $spAssignment

Next step is to get the list:
$SPList = $SPWeb.Lists["Announcements"]

When we have located the list we can retrieve the item. The quickest way is to use the GetItemByID() method:
$SPItem = $SPList.GetItemById("1")

The example above requires that you know the ID of the item. If you don’t know the items ID you can use the Where-Object cmdlet instead:

$SPItem = $SPList.Items | Where { $_["Title"] -eq "New Announcement" }
When you’ve retrieved the item you can modify the item information.

$SPItem[“Title”] = "MyTitle"
$SPItem[“Body”] = "MyBody"

After modifying an item you have to call the Update() method to set the changes.
$SPItem.Update()

When you’re done, use the Stop-SPAssignment cmdlet to dispose the SPWeb object. Stop-SPAssignment $SPAssignment

Delete List Item:

The example below will count the items and loop down, read the name of the item, and if the item contains a 3, then it will delete that item.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$site = new-object Microsoft.SharePoint.SPSite("http://test.tomdaly.com") # is a legit url
$relweburl = '/Docs"
$web = $site.openweb($relweburl)
$list=$web.Lists["testList"] $listItems = $list.Items
$listItemsTotal = $listItems.Count

for ($x=$listItemsTotal-1;$x -ge 0; $x--)
{
if($listItems[$x].name.Contains("3"))
{
Write-Host("DELETED: " + $listItems[$x].name)
$listItems[$x].Delete()
}
}

No comments:

Post a Comment