3

我的 powershell 脚本中有这段代码,它在特殊字符部分上表现不佳。

 $request = 'http://151.80.109.18:8082/vrageremote/v1/session/players'
 $a = Invoke-WebRequest -ContentType "application/json; charset=utf-8" $request |
 ConvertFrom-Json    |
 Select -expand Data |
 Select -expand players |
 Select displayName, factionTag | Out-file "$scriptPath\getFactionTag.txt"

在我的输出文件中,我只得到 '????' 对于任何特殊字符。有谁知道我怎样才能让它在我的输出文件中显示特殊字符?

4

3 回答 3

7

Peter Schneider 的有用答案Nas 的有用答案都解决了您的方法的一个问题:您需要:

  • 要么:访问.Content返回的响应对象上的属性Invoke-WebRequest以获取返回的实际数据(作为 JSON 字符串),然后您可以将其传递给ConvertFrom-Json.

  • or: use Invoke-RestMethodinstead,它直接返回数据并将其解析为自定义对象,因此您可以直接使用这些对象,而无需ConvertTo-Json; 但是,对于这种情况下的字符编码问题,这不是一个选项,因为需要对 JSON 字符串进行显式重新编码 - 见下文。

但是,您仍然遇到字符编码问题,因为在响应标头中没有charset信息的情况下,PowerShell 会将返回为ISO-8859-1编码的 UTF-8 编码 JSON 字符串解释(从 PowerShell 7.0 起仍然适用) .

有两种可能的解决方案:

  • 最好将 Web 服务修改为包含charset=utf-8在响应标头的ContenType字段中。

  • 如果你不能这样做,你必须明确地重新编码接收到的字符串以纠正字符编码的误解。

这是后者的实现:

$request = 'http://151.80.109.18:8082/vrageremote/v1/session/players'
$a = Invoke-WebRequest -ContentType "application/json; charset=utf-8" $request

# $a.Content now contains the *misinterpreted* JSON string, so we must 
# obtain its byte representation and re-interpret the bytes as UTF-8.
# Encoding 28591 represents the ISO-8859-1 encoding - see https://docs.microsoft.com/en-us/windows/desktop/Intl/code-page-identifiers
$jsonCorrected = [Text.Encoding]::UTF8.GetString(
  [Text.Encoding]::GetEncoding(28591).GetBytes($a.Content)
)

# Now process the reinterpreted string.
$jsonCorrected |
  ConvertFrom-Json    |
  Select -expand Data |
  Select -expand players |
  Select displayName, factionTag | Out-file "$scriptPath\getFactionTag.txt"
于 2018-10-28T18:05:08.500 回答
2

尝试将.Content属性的值转换为 JSON:

$request = 'http://151.80.109.18:8082/vrageremote/v1/session/players'
$a = Invoke-WebRequest -ContentType "application/json; charset=utf-8" $request

($a.Content | convertfrom-json).Data.Players | select DisplayName,FactionTag | Out-file "$scriptPath\getFactionTag.txt" -Encoding Default
于 2018-10-28T16:19:06.483 回答
2

如果Invoke-RestMethod您只需要 json 数据而没有ParsedHtml,Headers和其他返回的对象,请使用Invoke-WebRequest

$request = 'http://151.80.109.18:8082/vrageremote/v1/session/players'
$a = Invoke-RestMethod -ContentType "application/json; charset=utf-8" $request |
Select -expand Data |
Select -expand players |
Select displayName, factionTag | Out-file "$scriptPath\getFactionTag.txt"
于 2018-10-28T16:31:23.877 回答