当我尝试使用 aws cloud cli 通过 powershell 为多个实例创建 cloudwatch 警报时(如下)
$instanceNames = "i-000000123456789", "i-000000123456777";
foreach ($instanceName in $instanceNames) {
aws cloudwatch put-metric-alarm --alarm-name 'Major Alert > Memory Usage exceeds 90%' --alarm-description 'Major Alert > Memory Usage exceeds 90%' --actions-enabled --alarm-actions 'arn:aws:sns:us-east-1:123456789:Test_Topic' 'arn:aws:sns:us-east-1:123456777:Test_Topic' --metric-name 'Memory % Committed Bytes In Use' --namespace 'CWAgent' --statistic 'Average' --dimensions '[{"Name":"InstanceId","Value":"'$instanceName'"}]' --period 300 --evaluation-periods 1 --datapoints-to-alarm 1 --threshold 90 --comparison-operator 'GreaterThanThreshold' --treat-missing-data 'missing'
}
我收到以下错误消息:
格式化字符串时出错:输入字符串的格式不正确。 行:4 字符:1
+ CategoryInfo : InvalidOperation: ({0}"}]:String) [], RuntimeException
+ FullyQualifiedErrorId : FormatError
格式化字符串时出错:输入字符串的格式不正确。 行:4 字符:1
+ CategoryInfo : InvalidOperation: ({0}"}]:String) [], RuntimeException
+ FullyQualifiedErrorId : FormatError
即使我只是运行 cloudwatch cli 命令来创建警报 - 我在解析 json 语法时也会遇到相同的错误 “值”:“'+$实例名称+'”
对此的任何意见都将受到高度赞赏!
最后一部分解析错误:
先生,寻求您最后的帮助: 这是逐字字符串
'[{"Name":"instance","Value":"C:"},{"Name":"InstanceId","Value":"i-0123abcxyz"},{"Name":"objectname","Value":"LogicalDisk"}]' and I have parsed it with the below one theway you showed "[{"\`Name\`":"\`instance\`","\`Value\`":"\`C:\`"},{\`"Name\`":\`"InstanceId\`",\`"Value\`":\`"'$instanceName'\`"},{"\`Name\`":"\`objectname\`","\`Value\`":"\`LogicalDisk\`"}]" but still I'm getting error.
我还遗漏了什么吗?仍然显示格式不正确。对此有何回应
有两个问题:
您正在尝试使用字符串插值,但您正在使用逐字(单引号)字符串(
'...'
),其中嵌入的变量引用(例如$instanceName
)是设计使然的不是扩展(插值)。
您必须使用可扩展(双引号)字符串(
"..."
)进行字符串插值(有关PowerShell字符串插值的语法和规则的简明摘要,请参阅这个答案)。
在此类字符串内,任何 embedded
"
字符。必须转义为 `"
或 ""
。
由于 Windows PowerShell 和 PowerShell(核心)(直至 v7.2.x)中存在长期存在的错误,传递给 外部程序
的参数中嵌入的
"
字符必须手动使用 \
进行转义(请注意,对于 PowerShell 本身 \
没有特殊含义)。
--dimensions
论点表述如下:
--dimensions "[{\`"Name\`":\`"InstanceId\`",\`"Value\`":\`"$instanceName\`"}]"
\
- 转义
"
):
--dimensions "[{`"Name`":`"InstanceId`",`"Value`":`"$instanceName`"}]"
程序化转义和替代解决方案,请参阅此答案。