仅在 us-east-1 区域一次又一次在 powershell 中使用 aws cli 时遇到奇怪的问题,但在其他区域脚本工作正常。
我正在尝试构建一个逻辑,借助以下脚本来获取现有的警报详细信息:
$alarmNames = aws cloudwatch --profile $profile --region $region describe-alarms --query MetricAlarms[].AlarmName[] --output json | ConvertFrom-Json
这给了我一个奇怪的错误,即
aws :
At line:525 char:15
+ ... larmNames = aws cloudwatch --profile $awsProfile --region $awsRegion ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
'charmap' codec can't encode character '\uf13f' in position 75: character maps to <undefined>
ConvertFrom-Json : Invalid array passed in, ',' expected. (7840): [
Write-Output ( "data type is "+$alarmNames.GetType())
abobe 错误在这一行指向我,但在其他区域同样可以正常工作,没有任何编码问题
$alarmNames = aws cloudwatch --profile $profile --region $region 描述警报 --query MetricAlarms[].AlarmName[] --output json | ConvertFrom-Json
上面的查询正在获取 System.Object[] 类型数据类型
任何输入或想法我应该如何避免我的 powershell aws cli 脚本中的此异常/错误?
听起来
aws.exe
在幕后使用 Python,并且要打印到 stdout 的文本包含无法在隐式输出字符编码中进行编码的 Unicode 字符
(请注意,输出中的 PRIVATE USE-F13F、U+F13F
)字符肯定不寻常)。
也许以下内容有帮助 - 我无法亲自验证:
在 aws
调用之前
从 PowerShell 执行以下操作:
Python 产生 UTF-8 输出(根据定义,它能够编码所有 Unicode 字符),通过如下设置 PYTHONIOENCODING
环境变量(默认情况下未定义):
$env:PYTHONIOENCODING='utf-8'
aws.exe
遵循与直接使用 Python 相同的环境变量。
PowerShell interpret aws.exe
输出为 UTF-8 编码,以确保其正确解码为 .NET 字符串:
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
# Save the current settings.
$prevEnvVar = $env:PYTHONIOENCODING; $prevEnc = [Console]::OutputEncoding
# Tell aws.exe / Python to output UTF-8.
$env:PYTHONIOENCODING='utf-8'
# Tell PowerShell to interpret the output from external programs
# such as aws.exe as UTF-8.
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
# Make the aws call, whose output should now be UTF-8 and which
# PowerShell should interpret as such.
$alarmNames =
aws cloudwatch --profile $profile --region $region describe-alarms --query MetricAlarms[].AlarmName[] --output json |
ConvertFrom-Json
# Restore the previous settings.
$env:PYTHONIOENCODING = $prevEnvVar; [Console]::OutputEncoding = $prevEnc