在 PowerShell 中通过 aws cli 创建 cloudwatch 警报时出现字符串解析错误

问题描述 投票:0回答:1

当我尝试使用 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

  • aws cloudwatch put-metric-alarm --alarm-name '主要警报 > 记忆我们...
  •   + CategoryInfo          : InvalidOperation: ({0}"}]:String) [], RuntimeException
      + FullyQualifiedErrorId : FormatError
    
    

格式化字符串时出错:输入字符串的格式不正确。 行:4 字符:1

  • aws cloudwatch put-metric-alarm --alarm-name '主要警报 > 记忆我们...
  •   + 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.

我还遗漏了什么吗?仍然显示格式不正确。对此有何回应

json powershell aws-cli amazon-cloudwatch
1个回答
1
投票

有两个问题:

  • 您正在尝试使用字符串插值,但您正在使用逐字(单引号)字符串(

    '...'
    ,其中嵌入的变量引用(例如
    $instanceName
    )是设计使然的不是扩展(插值)。

  • 由于 Windows PowerShellPowerShell(核心)(直至 v7.2.x)中存在长期存在的错误,传递给 外部程序

    的参数中嵌入的 
    " 字符必须手动使用 \
     进行转义(请注意,对于 PowerShell 本身 
    \
     没有
    特殊含义)。

因此,将你的

--dimensions

 论点表述如下:

  • 直至 PowerShell 7.2.x:

    --dimensions "[{\`"Name\`":\`"InstanceId\`",\`"Value\`":\`"$instanceName\`"}]"
    
    
  • 在 PowerShell 7.3+ 中(不再需要手动

    \

     - 转义 
    "
    ):

    --dimensions "[{`"Name`":`"InstanceId`",`"Value`":`"$instanceName`"}]"
    
    
对于 Windows PowerShell 和 PowerShell (Core) 7.2.x 及更低版本中的

程序化转义和替代解决方案,请参阅此答案

© www.soinside.com 2019 - 2024. All rights reserved.