SharePoint API Invoke-RestMethod PowerShell

Invoke-RestMethod was introduced in PowerShell 3.0, but unfortunately there is a bug that prevents the user from setting the “Accept” header. The SharePoint 2013 REST API requires special values applied to the Accept header to return common items like list data. A typical example to retrieve contents of a list might look like:

  • $restData = Invoke-RestMethod -UseDefaultCredentials -Headers @{ "Accept" = "application/json;odata=verbose" } "http://server/site/_api/lists/getbytitle('listname')/items"

If you’re running a version of PowerShell older than 4.0, this will fail to set the Accept header and will return an error. If you attempt to retrieve the data without the header, it will be incomplete (missing actual data). PowerShell 4.0 is included with Windows 8.1 and Server 2012 R2. You can download “Windows Management Framework (WMF) 4.0” for Windows 7 and Server 2008 R2 (Win7 or 2008 R2 = Windows NT 6.1). Newer versions of PowerShell should also contain the fix.

Another nasty bug related to PowerShell handling of SharePoint JSON list data – default list properties include DUPLICATE “Id” and “ID” fields. If you attempt to convert a JSON string with these duplicates using ConvertFrom-Json, it will fail with an error. One rough workaround is to replace all the duplicate Id’s with a Non-duplicate Id. Another better workaround would be to explicitly use ODATA “$select” to choose only specific columns for SharePoint to return (eliminating the duplicate without rough string replace). The real trouble is with PowerShell JSON de-serialize implementation – it creates properties that must be case-insensitive (because ALL Identifiers in PowerShell are NOT case sensitive). Here’s an example of rough conversion of the duplicate key property (using $restData from above). Inspired by @JPBlanc answer to “ConvertFrom-Json … contains the duplicated keys.” (

  • $json = ($restData -creplace '"Id":', '"Idx":') | ConvertFrom-Json

I won’t provide an ODATA $select example here, but there should be plenty available with a quick Google search. Another advantage to the $select approach is an improvement in performance – only sending the data you actually want to use.


About notesbytom

Keeping technology notes on to free up my mind to solve new problems rather than figuring out the same ones repeatedly :-).
This entry was posted in System Administration and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s