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".
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.