Deleting SharePoint Items remotely via Powershell

Recently I was trying to put together a really quick solution to delete some SharePoint 2010 items remotely using Powershell script. It'd be quite usual to incorporate CSOM into such a solution, but as I had some legacy powershell performing actions via the SharePoint web services (lists.asmx) it seemed like I could hack it together quicker that way. How wrong I was!

To cut a long story short it turned out that the MSDN documentation on this is wrong! This led to head scratching and a much slower resolution than I was after.

The MSDN documentation is here;

Some wrong MSDN Docco

This tells you that to delete multiple list items you need to build a package for the web service call like this;

<Batch OnError="Continue" ListVersion="1" 

ViewName="270C0508-A54F-4387-8AD0-49686D685EB2">

<Method ID="1" Cmd="Delete">

  &lt;Field Name='ID'&gt;2&lt;/Field&gt;

</Method>

<Method ID="2" Cmd="Delete">

  &lt;Field Name='ID'&gt;8&lt;/Field&gt;

</Method>

</Batch>

See how it just requires the ID values? WRONG!

It turns out it needs the FileRef attribute too otherwise you're in a world of pain;

<Batch OnError="Continue" ListVersion="1" 

ViewName="270C0508-A54F-4387-8AD0-49686D685EB2">

<Method ID="1" Cmd="Delete">

  &lt;Field Name='ID'&gt;2&lt;/Field&gt;&lt;Field Name="fileRef"&gt;<br />http://domain/sites/TheSite/TheLibrary/The File 223.pdf&lt;/Field&gt;

</Method>

<Method ID="2" Cmd="Delete">

  &lt;Field Name='ID'&gt;8&lt;/Field&gt;&lt;Field Name="fileRef"&gt;<br />http://domain/sites/TheSite/TheLibrary/The File 991.pdf&lt;/Field&gt;

</Method>

</Batch>

 

So assuming you've put the above XML together in your powershell, how do you invoke the delete via web services? Like this;

$batchElement = [The XML from above]

$SiteName = "http://MyDomain/sites/TheSite"

$listName = "TheLibrary"

$ServiceDesc = $SiteName + "/_vti_bin/lists.asmx?WSDL"

$service = New-WebServiceProxy -UseDefaultCredential -uri $ServiceDesc

$results = $service.UpdateListItems($listName, $batchElement)

You can then check your $results XML for success codes (or other!)

Happy SharePointing!