powershell - 从超过1级深度的属性中从数组中提取项目?

标签 powershell

说我有一个元数据项数组。这样的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#等效的Powershellvar 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 user ParseExact() 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/

相关文章:

powershell - 如何禁用/覆盖 PowerShell 点符号

xml - 尝试获取XML元素

windows - 使用 "-noprofile"参数提升当前脚本

windows - 如何在PowerShell一线式中转义空间

powershell - Powershell-将文本递归地添加到子目录中文件名的末尾

php - 如何将投票按钮限制为 'To' 地址而不是通过 powershell 在 outlook 中发送到 'Cc'?

azure - 在 Service Fabric 中取消配置旧应用程序类型版本的策略

powershell - Powershell 中的运算符 <<<(shell)

powershell - 调试Powershell登录网页脚本

unit-testing - 如何在 *n* 个测试失败后停止 MsTest 测试执行