首页 > 解决方案 > 在powershell中重新排序对象成员

问题描述

我有以下用于特定测试的对象(它保存在 json 文件中并转换为对象):

TestID     : 1510242
Path       : example_designs/crr
2020/07/16 : _Failed_
2020/07/19 : _Failed_
2020/07/20 : _Failed_
07/22/2020 : _Failed_
07/23/2020 : _Passed_
07/26/2020 : _Passed_
07/27/2020 : _Pending_
07/28/2020 : _Passed_
07/29/2020 : _Passed_
07/30/2020 : _Running_

每天我添加一个成员 add-member -NotePropertyName $date -NotePropertyValue $testRsult并将其转换回 Json 文件。

问题是新成员是在最后添加的,所以当我展示它时,最新的结果在最后。有没有为什么要重新排序成员,或在特定位置添加新成员?

标签: jsonpowershell

解决方案


一个潜在的解决方案。而不是使用Add-Member存储计算的属性。将其插入现有属性的数组中,然后在Select-Object命令中引用该数组:

示例(在 PoSh 5.1 和 7.0 中测试):

$Date      = (Get-Date).ToString()
$TestResult = "Some test result"

$NewPropertyExpression =
@{
    Name       = $Date.ToString()
    Expression = { $TestResult }
}

$Object = [PSCustomObject]@{
    Property1 = "1"
    Property2 = "2"
    Property3 = "3"
    Property4 = "4"
    Property5 = "5"
    Property6 = "6"
    Property7 = "7"
}

$Properties = [Collections.ArrayList]$Object.PSObject.Properties.Name

$Properties.insert( 2, $NewPropertyExpression )

$Object | Select-Object $Properties

所以上面我在数组的第二个索引处插入了一个属性。输出如下:

Property1             : 1
Property2             : 2
7/31/2020 12:25:41 PM : Some test result
Property3             : 3
Property4             : 4
Property5             : 5
Property6             : 6
Property7             : 7

注意:我在您编辑问题之前已经这样做了,但它应该仍然有效。如果我有时间,我会编辑以匹配。

您也可以在插入之前对数组进行排序。如果您想进一步讨论订购等...有很多选择。


推荐阅读