Darktux
Darktux

Reputation: 427

How to sort a Multi Dimensional Array in Powershell

I have a script to cleanup a folder regularly. Every month there are 3-4 sub folders created; what i am trying to accomplish is keep a single folder per month and delete the rest on that folder on every server. I was successfull with the script, but ran into below block.

My array looks as below;

$Array = ((Filepath,Timestamp2),(Filepath,Timestamp3),(Filepath,Timestamp1),(Filepath,Timestamp4))

What i would like to do is, sort elements in array by timestamp; how to do that? Please let me know if any other questions regarding this.

Upvotes: 1

Views: 1976

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

My recommendation would be to convert the array of arrays into a list of custom objects and sort that list by the Timestamp property:

$array | ForEach-Object {
  New-Object -Type PSCustomObject -Property @{
    Filepath  = $_[0]
    Timestamp = $_[1]
  }
} | Sort-Object Timestamp

Upvotes: 1

Related Questions