说我有一个元数据项数组。这样的json数据如下所示:
[
{
"attributes": {
"created": "20/08/2020",
"valid": true,
"name": "foobar"
},
"id": 1
},
{
"attributes": {
"created": "22/08/2020",
"valid": true,
"name": "foobar"
},
"id": 3
}
]
我想做的是在数组中找到具有最新创建的数据的元数据项,并返回整个项元数据项(即这样,我仍然可以访问元数据的其他字段)。我正在尝试做这样的事情:
$myArray | Sort-Object -Property attributes.created | Select-Object -Last 1
但这不起作用,因为-Property
似乎只能与一级深度的属性一起使用。我想我正在尝试获得与C#等效的Powershell
var itemIWant = myArray.OrderByDescending(o => o.attributes.created).First();
我该如何实现?
最佳答案
如其他一些答案所示,您可以按表达式排序以获取子属性。可能看起来像:
$JSON =
@"
[
{
"attributes": {
"created": "20/08/2020",
"valid": true,
"name": "foobar"
},
"id": 1
},
{
"attributes": {
"created": "22/08/2020",
"valid": true,
"name": "foobar"
},
"id": 3
}
]
"@
$Objects = ConvertFrom-Json $JSON
$Objects |
Sort-Object -Property { [DateTime]::ParseExact( $_.Attributes.Created, "dd/MM/yyyy", $null ) } |
Select-Object -Last 1
Note: That that you have to convert the "Created" Property to a
[DateTim]
object to sort properly. That said the parsing approach in the other answers may not work unless you tell it how to parse it. In this example I userParseExact()
which in testing seems to do the trick.
鉴于从
ConverFrom-Json
返回的对象没有正确键入“Created”属性,因此您可能想在进行排序之前重铸它。这可能取决于您是否要对对象集合做其他任何事情。可能有几种方法可以执行此操作,但是这是在ConvertFrom-Json
命令之后执行的一种方法:$Objects.ForEach( { $_.Attributes.created = [DateTime]::ParseExact( $_.Attributes.Created, "dd/MM/yyyy", $null ) } )
现在,“Created”属性将是一个实际的[DateTime]
对象,您可以像其他日期一样对compare等进行排序。$Objects | Sort-Object -Property { $_.attributes.created } | Select-Object -Last 1
关于powershell - 从超过1级深度的属性中从数组中提取项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63619297/