Sunday, April 19, 2015

Delete an item from the list by using a CAML query Within a specifi range

[string] $web = "http://abc.abc.com/test";

#Considering Workflow history as an example

[string] $list = "Workflow History";

[string] $caml = "<Where><Lt><FieldRef Name=`"Modified`"/><Value Type=`"DateTime`">2011-3-1T00:00:00Z</Value></Lt></Where><OrderBy><FieldRef Name=`"ID`" Ascending=`"TRUE`"/></OrderBy>";

#Number of items ot delete in a batch

[int] $rowLimit = 5000;

[switch] $whatif = $false;

[System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$spsite = New-Object -TypeName "Microsoft.SharePoint.SPSite" -ArgumentList $web

$spweb = $spsite.OpenWeb()

$splist = $spweb.Lists[$list]

$query=new-object -TypeName "Microsoft.SharePoint.SPQuery"

$query.Query = $caml

$query.RowLimit = $rowLimit

$col = $null

$col=$splist.GetItems($query);

$count = $col.Count;

Write-Host ("Items Count to be Deleted = " + $count)

# Create batch remove CAML query

 $batchRemove = '<?xml version="1.0" encoding="UTF-8"?><Batch>';

 # The command is used for each list item retrieved

 $command = '<Method><SetList Scope="Request">' + $splist.ID +'</SetList><SetVar Name="ID">{0}</SetVar>’ + ‘<SetVar Name="Cmd">Delete</SetVar></Method>';

 foreach ($item in $col)

 {

   # Loop through each list item and add the string to the batch command

   $batchRemove += $command -f $item.Id;

 }

 $batchRemove += "</Batch>";

 #Write-Host ("BATCH  " + $batchRemove)

 # Remove the list items using the batch command

 $spList.ParentWeb.ProcessBatchData($batchRemove) | Out-Null

$spweb.Dispose()

$spsite.Dispose()

No comments:

Post a Comment