Over View:
I’m trying to automate updates to a SharePoint list using PowerShell via the Web service object. The end goal is to remove items all from the list, then import new data via a csv file.
Task 1, get items from a SharePoint list - done
Task 2 update/Add items in a share point List - pending < Need help with this part, I'm receiving an error.... See Below! >
Task 3, Remove all items in the list. - Pending
Not Started
Task 1
Powershell Code:
$listName = "DemoList"
$uri = "http://companyweb/_vti_bin/lists.asmx"
$xmlDoc = new-object System.Xml.XmlDocument
$query = $xmlDoc.CreateElement("Query")
$viewFields = $xmlDoc.CreateElement("ViewFields")
$queryOptions = $xmlDoc.CreateElement("QueryOptions")
$rowLimit = "0"
$service = New-WebServiceProxy -UseDefaultCredential -uri $uri
$list = $service.GetListItems($listName, "" , $query, $viewFields, $rowLimit, $queryOptions, "")
### testing - confirm row count
$list.data.row.count
##### Select all data
$list.data.row | Select * | Format-table
Task 2 Source Example
Powershell Code:
# Get name attribute values (guids) for list and view
$ndlistview = $service.getlistandview($listname, "")
$strlistid = $ndlistview.childnodes.item(0).name
$strviewid = $ndlistview.childnodes.item(1).name
# Create an xmldocument object and construct a batch element and its attributes.
$xmldoc = new-object system.xml.xmldocument
# note that an empty viewname parameter causes the method to use the default view
$batchelement = $xmldoc.createelement("batch")
$batchelement.setattribute("onerror", "continue")
$batchelement.setattribute("listversion", "1")
$batchelement.setattribute("viewname", $strviewid)
# Specify methods for the batch post using caml. to update or delete, specify the id of the #item, and to update or add, specify the value to place in the specified column
$id = 1
$xml = ""
# The row to be modified
$rowId = $list.data.row.ows_id
# New field value
$newsport ="soccer"
$xml += "<method id='$id' cmd='Update'>" +
"<field name='ID'>$rowId</field>" +
"<field name='Sport'>$newsport</field>" +
"</method>"
# Set the xml content
$batchelement.innerxml = $xml
$ndreturn = $null
try {
$ndreturn = $service.updatelistitems($listname, $batchelement)
}
catch {
write-error $_ -erroraction:'stop'
}
Error : Update failed
Exception calling "UpdateListItems" with "2" argument(s): "Exception of type Microsoft.SharePoint.SoapServer.SoapServerException' was thrown." At line:98 char:41
Task 3 Pending