循环遍历Powershell中的单个ID



我在AWS中运行以下命令:

$ aws ec2 describe-images 
--owners self 
--query 'reverse(sort_by(Images,&CreationDate))[:5].{id:ImageId,date:CreationDate}'
[
{
"id": "ami-0a1b2c3d4e5f60001",
"date": "2018-11-28T17:16:38.000Z"
},
{
"id": "ami-0a1b2c3d4e5f60002",
"date": "2018-09-15T13:51:22.000Z"
},
{
"id": "ami-0a1b2c3d4e5f60003",
"date": "2018-08-19T10:22:45.000Z"
},
{
"id": "ami-0a1b2c3d4e5f60004",
"date": "2018-05-03T12:04:02.000Z"
},
{
"id": "ami-0a1b2c3d4e5f60005",
"date": "2017-12-13T17:16:38.000Z"
}
]

我想为每个单独的id使用foreach循环。我已经尝试过用文本输出来实现这一点,但是,foreach循环只会获取第一个id。我是编程新手,不知道如何实现这一目标。我仅限于Powershell。

如果您在变量$json中捕获此JSON格式的输出,您可以执行以下操作来迭代各个id属性:

# convert the JSON text to an array of PSObjects and loop through
($json | ConvertFrom-Json) | ForEach-Object {
# do something using the items id property
"Found ID: $($_.id)"
}

或者,如果你喜欢做一些不同的事情,你可以使用

$allItems = $json | ConvertFrom-Json
foreach ($item in $allItems) {
# do something using the items id property
"Found ID: $($item.id)"
}

需要$()构造来确保PowerShell将$item.id的值扩展到字符串中。您可以通过执行"Found ID: {0}" -f $item.id来获得相同的输出字符串

最新更新