1

I am trying to use the Invoke-Restmethod to call a set of API's, but i have a problem with output encoding. What it could be

$PSDefaultParameterValues['*:Encoding'] = 'utf8'    
$Header = @{"Authorization" = "Token token_value"}
    
    $uri = "https://some_api_url"
    $team = Invoke-RestMethod -Method GET -Uri $uri -Headers $Header -ContentType "text/*; charset=utf8"
    $team.last_name

Results:

enter image description here

PS Version:

enter image description here

Encoding Config in PS enter image description here

website config:

enter image description here

mklement0
  • 382,024
  • 64
  • 607
  • 775
elpe
  • 33
  • 2
  • Save your PowerShell script in UTF8 – Theo Jun 23 '22 at 13:26
  • What matter is whether the _response_ from the web service indicates in its header that it is returning UTF-8. Does it? If not, and you have no way to change that, you'll have to manually _re-encode_ the response string and decode it again, as shown in [this answer](https://stackoverflow.com/a/53034595/45375). If that solves your problem, we can close this question as a duplicate. – mklement0 Jun 23 '22 at 13:50
  • I know the problem is with Invoke command. It get data in windows-1252 encoding and saves it in utf-8 format but without decoding. – elpe Jun 24 '22 at 06:22
  • If there's no `charset` header in the response, PowerShell assumes ISO-8859-1 encoding and that's what it uses to _decode_ the response into a .NET string (internally composed of UTF-16 code units). If the _actual_ encoding of the response is UTF-8, the decoding malfunctions. The previously linked answer shows you how to fix that problem _afterwards_. Have you tried it, and if it didn't work, how did it fail? – mklement0 Jun 24 '22 at 13:22
  • Saving to json and then editing data resolve problem with encoding `$f = 'D:\temp\out.json' Invoke-RestMethod -Method GET -Uri $url -Headers $Header -OutFile $f $json = Get-Content -Path $f -Encoding UTF8 | Out-String | ConvertFrom-Json` – elpe Jun 24 '22 at 21:00
  • This confirms that your question is a duplicate, so I've marked it as such. Your solution is conceptually simpler, but less efficient (the efficiency can be improved by omitting `Out-String` and using `-Raw` with `Get-Content`), though in practice that may not matter. I encourage you to post your solution as an answer to the linked duplicate. – mklement0 Jun 25 '22 at 02:39

0 Answers0