You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中转换含特殊字符的AWS CLI JSON字符串为对象

问题:PowerShell处理AWS CLI返回JSON时的特殊字符解码错误

我尝试用PowerShell将AWS CLI获取的JSON字符串转换为JSON对象,但部分场景下字符串包含无法解码的特殊字符,报错:

'charmap' codec can't encode character '\u2192' in position 681: character maps to <undefined>

完整错误信息如下:

ConvertFrom-Json: Scripted.ps1:18:19
Line |
  18 |      $res = $res | ConvertFrom-Json
     |                    ~~~~~~~~~~~~~~~~
     | Conversion from JSON failed with error: Unexpected end when reading token. Path 'Findings[98]'.

我使用的代码:

$res = aws securityhub get-findings
$res = $res | ConvertFrom-Json

请问是否有办法删除该特殊字符或正确解码它?

我按照@bcbabrich的回答添加了以下代码,但仍出现相同错误:

$enc = [System.Text.Encoding]::UTF8
$res = aws securityhub get-findings
$decoded = $enc.GetBytes($res)
$encoded = [System.Text.Encoding]::UTF8.GetString($decoded)
$encoded = $encoded | ConvertFrom-Json
$res = $encoded

解决方案

方法1:强制AWS CLI输出UTF-8编码内容

AWS CLI默认输出编码可能与PowerShell不兼容,直接指定CLI输出UTF-8编码,从根源解决字符问题:

# 设置环境变量强制AWS CLI用UTF-8输出
$env:AWS_CLI_ENCODING = 'utf-8'
# 执行命令并直接转换为JSON对象
$res = aws securityhub get-findings | ConvertFrom-Json

方法2:清理字符串中的无效特殊字符

如果方法1无效,可在转换前过滤掉非可打印的特殊字符,只保留有效UTF-8字符:

$res = aws securityhub get-findings
# 过滤掉非字母、数字、标点、空白的无效字符
$cleanedRes = $res -replace '[^\p{L}\p{N}\p{P}\p{Z}]', ''
$res = $cleanedRes | ConvertFrom-Json

方法3:用.NET进程流读取输出

PowerShell直接捕获命令输出可能存在编码丢失,改用.NET的Process类读取CLI输出流,确保编码正确:

$processInfo = New-Object System.Diagnostics.ProcessStartInfo
$processInfo.FileName = 'aws.exe'
$processInfo.Arguments = 'securityhub get-findings'
$processInfo.RedirectStandardOutput = $true
$processInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8
$processInfo.UseShellExecute = $false

$process = [System.Diagnostics.Process]::Start($processInfo)
$rawOutput = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()

$res = $rawOutput | ConvertFrom-Json

内容的提问来源于stack exchange,提问作者Quentin_otd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 01:35:15