reorder object members in powershell

Viewed 67

I have the following object for a specific test (it's held in a json file and converted into an object):

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_

each day I add a member add-member -NotePropertyName $date -NotePropertyValue $testRsult and convert it back to a Json file.

the problem is that the new member is added at the end, so when I present it, the newest result is at the end. is there a why to reorder the members, or add a new member in a specific location??

1 Answers

A potential solution. Instead of using Add-Member store a calculated property. Insert it into an array of existing properties, then reference the array in aSelect-Object command:

Example (Tested in 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

So above I'm inserting a property at the second index of the array. Output is like:

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

Note: I did this before you edited the question, but it should still be valid. If I have time I will edit to match.

You can potentially sort the array before the insert as well. If you wanted to further workshop the ordering etc... there are options.

Related