0

I'm trying to upload a file to SharePoint Online from a Powershell script via Invoke-RestMethod When I use a hash table as the header the response says the entity wants a JSON header. When I convert the header to JSON it says it can't bind the header because it can't convert a type string to a type IDictionary.

$Header = @{"Authorization" = "Bearer $accessToken"}

or

$Header = @{"Authorization" = "Bearer $accessToken"} | ConvertTo-Json

Invoke-RestMethod -Uri $Url -Headers $Header -Method Put -Infile $Path -ContentType 'multipart/form-data' -Verbose

What am I missing?

Response to comments:

I have copied the token generated by the script into a request in Postman and got a 200 response with valid data.

Error with header as hash table: { "error": { "code": "BadRequest", "message": "Entity only allows writes with a JSON Content-Type header.", "innerError": { "date": "2024-04-26T18:26:15", "request-id": "a870d677-7903-4417-a360-6abfbd056554", "client-request-id": "a870d677-7903-4417-a360-6abfbd056554" } } }

Error with header as JSON: Cannot bind parameter 'Headers'. Cannot convert the "{ "Authorization": "Bearer eyJ0e...COMPLETE TOKEN HERE...dswWw" }" value of type "System.String" to type "System.Collections.IDictionary".

3
  • Does you hash table contain arrays?
    – jdweng
    Commented Apr 25, 2024 at 23:49
  • Can you post the exact error messages for each case? (Edit your original post rather than post them as a comment)
    – mclayton
    Commented Apr 26, 2024 at 0:07
  • My guess is the website is expecting a JWT string in the $accessToken auth header but what you’re sending it isn’t in the correct format for whatever reason - in that case you need to use the first version of your headers, but fix the problem with your access token value…
    – mclayton
    Commented Apr 26, 2024 at 0:19

1 Answer 1

0

For future travelers, it turned out the error message didn't have much to do with the error. The header did not need to be converted to JSON. The problem was in the -Uri parameter:

Invoke-RestMethod -Uri $Url -Headers $Header -Method Put -Infile $Path -ContentType 'multipart/form-data' -Verbose

I had:

$Url = "https://graph.microsoft.com/v1.0/$TenantId/sites/$SiteId/drives/$LibraryId/items/root`:/$Filename/content"

Which needed to be:

$Url = "https://graph.microsoft.com/v1.0/$TenantId/sites/$SiteId/drives/$LibraryId/items/root:/$Filename:/content"

Note the backtick before the semicolon and $Filename variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.