使用 ListData.svc 和 PowerShell 更新 SharePoint 列表条目

Update SharePoint list entry using ListData.svc and PowerShell

有没有办法使用 PowerShell 更新 SharePoint 2010 列表条目,而无需使用 SharePoint 客户端?如果可以,怎么做?

要获得所需的字段,我会:

$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

我想修改 EndingDateHours 字段。

以下示例演示如何使用 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
}

用法

#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

作为替代方案,您也可以使用 Invoke-RestMethod instead of Invoke-WebRequest,例如:

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