如何用PowerShell从AWS JSON中提取指定字段(交互式管道方式)
PowerShell原生方式处理CloudFormation Stack Events JSON
嘿,刚好能帮到你!我完全理解你想抛弃bash那套外部工具+字符串处理,转而用PowerShell原生管道来搞定JSON解析的需求——毕竟既然用了跨平台的PowerShell Core,就得用它的正确姿势对吧?
PowerShell的核心优势是对象管道,不像bash是字符串流,所以处理JSON时我们不需要做字符串切割,直接把JSON转换成PowerShell对象后操作属性就行,这就是你要的「PowerShell标准方式」™。
对应你bash命令的PowerShell一行实现
aws cloudformation describe-stack-events --stack-name some-stack-here | ConvertFrom-Json | ForEach-Object { $_.StackEvents } | ForEach-Object { "$($_.Timestamp) $($_.ResourceStatus) $($_.ResourceType) $($_.ResourceStatusReason)" }
逐段解释每个部分
aws cloudformation ...: 和bash里一样,调用AWS CLI输出JSON格式的栈事件数据ConvertFrom-Json: 把JSON字符串转换成PowerShell自定义对象,这是关键一步——从此你可以直接用.访问JSON里的字段,不用再搞字符串解析ForEach-Object { $_.StackEvents }: 展开顶层对象里的StackEvents数组,让数组里的每个事件对象单独进入管道(相当于jq里的.StackEvents[])- 最后一个
ForEach-Object: 用PowerShell的字符串插值($()语法)提取每个事件的指定字段,拼接成你需要的格式。如果某个字段(比如ResourceStatusReason)为空,会自动留空,和jq的效果一致
更简洁的交互式版本(用别名)
在PowerShell的REPL环境里,你可以用别名让命令更短,输入更快:
aws cloudformation describe-stack-events --stack-name some-stack-here | ConvertFrom-Json | % StackEvents | % { "$($_.Timestamp) $($_.ResourceStatus) $($_.ResourceType) $($_.ResourceStatusReason)" }
这里的%是ForEach-Object的别名,% StackEvents是ForEach-Object { $_.StackEvents }的简写,交互式环境里用起来特别顺手。
测试你的示例JSON
如果你想用你提供的示例JSON测试,可以把JSON存到变量里跑:
$sampleJson = @" { "StackEvents": [ { "StackId": "arn:aws:cloudformation:some-region-here:some-number-here:stack/some-stack-here/some-id-here", "EventId": "some-event-id-here", "ResourceStatus": "UPDATE_COMPLETE", "ResourceType": "AWS::CloudFormation::Stack", "Timestamp": "some-date-here", "StackName": "some-stack-here", "PhysicalResourceId": "arn:aws:cloudformation:some-region-here:some-number-here:stack/some-stack-here/some-id-here", "LogicalResourceId": "some-stack-here" }, { "StackId": "arn:aws:cloudformation:some-region-here:some-number-here:stack/some-stack-here/some-id-here", "EventId": "some-event-id-here", "ResourceStatus": "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", "ResourceType": "AWS::CloudFormation::Stack", "Timestamp": "some-date-here", "StackName": "some-stack-here", "PhysicalResourceId": "arn:aws:cloudformation:some-region-here:some-number-here:stack/some-stack-here/some-id-here", "LogicalResourceId": "some-stack-here" } ] } "@ $sampleJson | ConvertFrom-Json | % StackEvents | % { "$($_.Timestamp) $($_.ResourceStatus) $($_.ResourceType) $($_.ResourceStatusReason)" }
运行后会输出你期望的结果:
some-date-here UPDATE_COMPLETE AWS::CloudFormation::Stack some-date-here UPDATE_COMPLETE_CLEANUP_IN_PROGRESS AWS::CloudFormation::Stack
为什么这是PowerShell的标准方式?
因为我们全程在操作对象,而不是字符串——PowerShell会帮你处理JSON的结构解析,你只需要关注要提取的属性,比bash里依赖jq的字符串处理更可靠,也更符合PowerShell的设计哲学。
内容的提问来源于stack exchange,提问作者oblio
相关产品推荐
相关产品推荐

