Search code examples
powershellsharepointsharepoint-2010odatapowershell-3.0

Update SharePoint list entry using ListData.svc and PowerShell


Is there a way to update a SharePoint 2010 list entry using PowerShell without using the SharePoint client? If so, how?

To get the desired fields, I would:

$url = 'http://myserver/resource/_vti_bin/ListData.svc/TheList(1234)?$select=Id,Title,StartingDate,Hours'

$webRequest = Invoke-WebRequest -Uri $url -Method Get -UseDefaultCredentials
[xml]$xml = $webRequest.Content

$properties = $xml.feed.entry.content.properties
$properties | Format-Table -Property Id,Title,StartingDate,EndingDate,Hours

I would like to modify the EndingDate and Hours fields.


Solution

  • The following example demonstrates how to update List Item using SharePoint REST Interface:

    <#
    .Synopsis
        Update Lst Item
    .DESCRIPTION
        Updates List Item operation using SharePoint 2010 REST Interface.
        To  update an existing entity, you must perform the following actions:
          - Create an HTTP request using the POST verb.
          - Add an X-HTTP-Method header with a value of MERGE.
          - Use the service URL of the list item you want to update as the target for the POST
          - Add an If-Match header with a value of the entity’s original ETag.
        Follow http://blog.vgrem.com/2014/03/22/list-items-manipulation-via-rest-api-in-sharepoint-2010/ for a more details
    .EXAMPLE
       Update-ListItem -WebUrl "http://contoso.intranet.com" -ListName "Tasks" -ItemId 1 -Properties $ItemProperties
    #>
    Function Update-ListItem()
    {
    Param(
      [Parameter(Mandatory=$True)]
      [string]$WebUrl,
      [Parameter(Mandatory=$True)]
      [string]$ListName,
      [Parameter(Mandatory=$True)]
      [int]$ItemId, 
      [Parameter(Mandatory=$True)]
      [Hashtable]$Properties
    )
    
        #construct endpoint for updaing of List Item   
        $endpointUrl = "$WebUrl/_vti_bin/listdata.svc/$ListName($ItemId)"
    
        $headers = @{
           "X-HTTP-Method" = "MERGE";
           "If-Match" = "*"
        }
    
        $ItemPayload = $Properties | ConvertTo-Json
    
        Invoke-WebRequest -Uri $endpointUrl -Method Post -UseDefaultCredentials -Headers $headers -ContentType "application/json" -Body $ItemPayload
    }
    

    Usage

    #Update Task list item
    $ItemProperties = @{  
           Title = "Approval Task"; 
           StartDate = "2014-04-24T00:00:00"}
    Update-ListItem -WebUrl "http://contoso.intranet.com" -ListName "Tasks" -ItemId 1 -Properties $ItemProperties
    

    As an alternative you could also utilize Invoke-RestMethod instead of Invoke-WebRequest, for example:

    Invoke-RestMethod -Uri $EndpointUrl -Method Post -UseDefaultCredentials -Headers $headers -ContentType "application/json" -Body $ItemPayload