Sort a PSCustomObject by date in powershell

Viewed 36

I have a pscustomobject I created:

$data = [pscustomobject]@{
    CatWeeklyFiles = @()
}

I used a custom function to generate dates for items I am appending to it. The following is the appending code I run in a for loop.

 #Append to the data object
    $data.CatWeeklyFiles += @{
        FileName = $item.ToString()
        Exists = 1
        Date = $CatDate.ToString("MM-dd-yyyy")
    }

I export this at the end as JSON and this is an example of the first few lines. How can I sort this in powershell before exporting to JSON so that I can have the date ascending or descending? (Note: it already is in order ascending but I need to know how to change it).

{
    "CatWeeklyFiles":  [
                           {
                               "Date":  "04-13-2015",
                               "FileName":  "Week1615CatUpdate.exe",
                               "Exists":  1
                           },
                           {
                               "Date":  "04-20-2015",
                               "FileName":  "Week1715CatUpdate.exe",
                               "Exists":  1
                           },
                           {
                               "Date":  "04-27-2015",
                               "FileName":  "Week1815CatUpdate.exe",
                               "Exists":  1
                           },
                           {
                               "Date":  "05-04-2015",
                               "FileName":  "Week1915CatUpdate.exe",
                               "Exists":  1
                           }
]
}

Edit - Adding full code

####Setup 
$curDir = Get-Location
$filename = "files.txt"
$pathtocheck = "C:\path\In\Cat_Weekly"
#Create array from the files.txt file
$array = Get-Content $filename


##Function to get date from week/year
Function FirstDateOfWeek
{
param([int]$year, [int]$weekOfYear)

$jan1 = [DateTime]"$year-01-01"
$daysOffset = ([DayOfWeek]::Thursday - $jan1.DayOfWeek)

$firstThursday = $jan1.AddDays($daysOffset)
$calendar = ([CultureInfo]::CurrentCulture).Calendar;

$firstWeek = $calendar.GetWeekOfYear($firstThursday, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [DayOfWeek]::Monday)

$weekNum = $weekOfYear

if($firstweek -le 1) { $weekNum -= 1 }

$result = $firstThursday.AddDays($weekNum * 7)
return $result.AddDays(-3)    
}
##Create data structure for making JSON
$data = [pscustomobject]@{
    CatWeeklyFiles = @()
}


#TEST

#Main Loop
for($i=0; $i -lt $array.Length; $i++){

$item = $array[$i]
#This is for cat weekly files that DO exist.
if((Test-Path -Path $pathtocheck\$item -PathType Leaf) -eq $True){

    write-host $i " Update: " $item "exists"
    #Extract Week and Year Values
    $extWeek = $item.Substring(4,2)
    $extYear = "20"+$item.Substring(6,2)
        #This handles a bug where the year appears as '99 when it should be '19
        if ($extYear -eq 2099){
        $extYear = 2019
        }


    #Run Function
    $CatDate= FirstDateOfWeek -year $extYear -weekOfYear $extWeek
    
    #Append to the data object
    $data.CatWeeklyFiles += @{
        FileName = $item.ToString()
        Exists = 1
        Date = $CatDate.ToString("MM-dd-yyyy")

    }

}

#This is for cat weekly files that DON'T exist.

elseif((Test-Path -Path $pathtocheck\$item -PathType Leaf) -eq $False){

    write-host $i " Update: " $item "is missing!"
    #Extract Week and Year Values
    $extWeek = $item.Substring(4,2)
    $extYear = "20"+$item.Substring(6,2)
        #This handles a bug where the year appears as '99 when it should be '19
        if ($extYear -eq 2099){
        $extYear = 2019
        }

    #Run Function
    $CatDate= FirstDateOfWeek -year $extYear -weekOfYear $extWeek
    
    #Append to the data object
    $data.CatWeeklyFiles += @{
        FileName = $item.ToString()
        Exists = 0
        Date = $CatDate.ToString("MM-dd-yyyy")

    }
   }
}


#Output data object as json
$json = $data | ConvertTo-Json | Out-File $curDir\tracking.json

1 Answers

Our comment talk has gotten a little confusing I guess. ;-) Here to show what I meant ... If you have unsorted data input like this:

$InputData = @'
{
    "CatWeeklyFiles": [
        {
            "Date": "2015-04-27",
            "FileName": "Week1815CatUpdate.exe",
            "Exists": 1
        },
        {
            "Date": "2015-05-04",
            "FileName": "Week1915CatUpdate.exe",
            "Exists": 1
        },
        {
            "Date": "2015-04-13",
            "FileName": "Week1615CatUpdate.exe",
            "Exists": 1
        },
        {
            "Date": "2015-04-20",
            "FileName": "Week1715CatUpdate.exe",
            "Exists": 1
        }
    ]
}
'@ |
    ConvertFrom-Json

And you output it like this ...

$InputData.CatWeeklyFiles

it looks like this:

Date       FileName              Exists
----       --------              ------
2015-04-27 Week1815CatUpdate.exe      1
2015-05-04 Week1915CatUpdate.exe      1
2015-04-13 Week1615CatUpdate.exe      1
2015-04-20 Week1715CatUpdate.exe      1

Now you can use Sort-Object to sort it the way you want and safe it to a new vairable...

$NewData = 
    [pscustomobject]@{
        CatWeeklyFiles = 
            $InputData.CatWeeklyFiles | 
                Sort-Object -Property Date -Descending 
    }

When you output it now

$NewData.CatWeeklyFiles

It looks like this

Date       FileName              Exists
----       --------              ------
2015-05-04 Week1915CatUpdate.exe      1
2015-04-27 Week1815CatUpdate.exe      1
2015-04-20 Week1715CatUpdate.exe      1
2015-04-13 Week1615CatUpdate.exe      1

Now you can convert it to JSON and export it

$NewData | 
    ConvertTo-Json | 
        Out-File $curDir\tracking.json

And all of that just because we choose the proper format for the date. ;-)

Related