PowerShell Invoke-WebRequest non-ascii characters not appearing correctly

Tarkowski, Michael (M.) 156 Reputation points
2023-10-10T11:34:06.56+00:00

I'm using PowerShell 5.1 on Windows to request information from an API endpoint.

OS Name: Microsoft Windows 10 Enterprise

OS Version: 10.0.19045 N/A Build 19045

Using Postman I can make the API request that returns the following non-ascii information correctly.

{"schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],"name":{"formatted":"Kiên fguyễn Kiên fguyễn","familyName":"Kiên fguyễn"

,"givenName":"Kiên fguyễn"},"id":"47600169ID","userName":"549775779"}

In Powershell I'm using Invoke-WebRequest witht following code.

$url = "https://myApiEndpoint . . .

$contentTypeValue = "application/scim+json;charset=utf-8"

$authorization = "myApiAccessToken"

$methodType = "GET"

$acceptValue = '/'

$acceptEncoding = 'gzip, deflate, br'

$requestHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"

$requestHeaders.Add("Authorization", $authorization)

$requestHeaders.Add("Content-Type", $contentTypeValue)

$requestHeaders.Add("Accept", $acceptValue)

$requestHeaders.Add("Accept-Encoding", $acceptEncoding)

$post = Invoke-WebRequest -Uri $url -Method $methodType -Headers $requestHeaders

$post.Content returns the following non-ascii information incorrectly. Notice the non-ascii information is different than what is returned from Postman.

{"schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],"name":{"formatted":"Kiên fguyễn Kiên fguyễn","familyName" :"Kiên fguyễn","givenName":"Kiên fguyễn"},"id":"47600169ID","userName":"549775779"}

What can I do to convert the $post.Content output so that the non-ascii charaters appear correctly?

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,136 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Tarkowski, Michael (M.) 156 Reputation points
    2023-10-10T12:31:59.1933333+00:00

    Looks like this will work to make non-ascii readable
    $post = [System.Text.Encoding]::UTF8.GetString($([String]::new($post.Content)).ToCharArray())

    0 comments No comments