Friday, April 8, 2016

Powershell: Error invoking Invoke-RestMethod cmdlet

Inside a Powershell script I’m using I have the following line:

$headers = @{ "Accept" = "application/json; api-version=2.0-preview"; "X-TFS-FedAuthRedirect" = "Suppress" }

Invoke-RestMethod -Uri $url -Credential $Credential -Headers $headers -ContentType application/octet-stream -Method Put -InFile $taskZipItem

I’m using the Invoke-RestMethod cmdlet to call a REST api with some parameters. Although this worked perfectly on my machine(it always does isn’t it Smile), it failed on a colleagues machine with the following error message:

Invoke-RestMethod : The 'Accept' header must be modified using the appropriate property or method.

Parameter name: name

At C:\uploadtask.ps1:31 char:1

+ Invoke-RestMethod -Uri $url -Credential $Credential -Headers $headers -ContentTy ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [Invoke-RestMethod], ArgumentException

    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Some investigation brought us the answer. In Powershell v3 you cannot specify the Accept header when calling the Invoke-RestMethod. To solve this we upgraded to Powershell v4 and the error was gone. (That also explained why I had no issue as I was running Powershell v5).

No comments: