使用Powershell

时间:2018-06-01 08:34:32

标签: json powershell

现在,Powershell是开源和跨平台(使用Powershell Core),我想我会再试一次。

我过去曾经使用过,并且在某些时候已经想到了管道是如何工作的,但它并不是非常直观的。它应该是,但事实并非如此,所以我有点卡住......

手头的任务:从命令的JSON输出中解析并打印几个字段。我可以用老式的方式,外部命令和字符串处理,àlabash,但我想学习如何做到这一点 Powershell方式™。

为了澄清,我想以交互方式,在管道中进行。我不想写一个脚本,我想学习如何在一个人中进行这种处理 - 衬垫(或者最多2个,但基本上使用Powershell作为REPL,而不是作为脚本工具)。

Bash命令:

aws cloudformation describe-stack-events --stack-name some-stack-here | jq ".StackEvents[] | [.Timestamp, .ResourceStatus, .ResourceType, .ResourceStatusReason] | join(\" \")"

这样做是输入JSON并打印我感兴趣的3个字段。

输入JSON:

{
    "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"
        }
    ]
}

命令输出:

"some-date-here  UPDATE_COMPLETE  AWS::CloudFormation::Stack  "
"some-date-here  UPDATE_COMPLETE_CLEANUP_IN_PROGRESS  AWS::CloudFormation::Stack  "

(我认为这应该在Stackoverflow上,因为该主题涉及对Powershell概念的非常了解,包括.NET对象,更接近编程而不是系统管理,即SuperUser左右。)

1 个答案:

答案 0 :(得分:2)

你可以这样做:

$j = aws cloudformation describe-stack-events --stack-name some-stack-here | ConvertFrom-Json
$j.StackEvents | % { "{0} {1} {2}" -f $_.Timestamp, $_.Resourcestatus, $_.ResourceType }

使用ConvertFrom-Json cmdlet将命令结果存储到powershell对象中,然后您可以选择StackEvents数组并将其循环以选择所需的值。

如果你想在一行中这样做:

(aws cloudformation describe-stack-events --stack-name some-stack-here | ConvertFrom-Json).StackEvents | %
{ "{0} {1} {2}" -f $_.Timestamp, $_.Resourcestatus, $_.ResourceType }