Wednesday, April 25, 2018

How to use CAML Query in PowerShell to excute any operation

If you want to delete (or any operation) multiple Items from a list based on certain condition then you can refer below PowerShell command where we can use CAML query to get exact items which we need to delete. Most of the time I found that the developers write PowerShell command which get all the items then Check the condition and delete the items. If you have large number items in list then it will get much time to execute.

Add-PSSnapin Microsoft.SharePoint.Powershell -ea SilentlyContinue
$web = get-spweb "[Site URL]"
$list = $web.lists["List Name"]
$ValueToCompare = "[Value To Compare]"
$FieldToCompare = "[Field Name To Compare]"
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$query.RowLimit = 1000
$caml='<Where> <Eq> <FieldRef Name="'+$FieldToCompare+'" /><Value Type="Text">'+$ValueToCompare+'</Value> </Eq> </Where>'
Write-Host $caml
$query.Query = $caml
$query.ViewFields = "<FieldRef Name='ID'/>"
$query.ViewFieldsOnly = $true
do
{
  $listItems = $list.GetItems($query)
  $query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
  foreach($item in $listItems)
  {
    Write-Host "Deleting Item - $($item.Id)"
    $list.GetItemById($item.Id).delete()
  }
}
while ($query.ListItemCollectionPosition -ne $null)  


2 comments:

  1. Nice article.
    Is this possible to add multiple conditions in it?

    ReplyDelete
    Replies
    1. It seems you are the sole follower to my blog. Thanks for reading it. It motivates me more to write.

      Yes you can use multiple condition in where clause just you use in JSOM or CSOM.

      One thing I have noticed that google Blogger.com deleted my Code written in Tags. Do you know how we can embed our code snippet in Blogger.com?

      Delete