Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Sort with Custom Sorting Expression

I have a directory containing numbered directories:

Archive
 |-1
 |-2
 |-3
 |-...

I need to create the next directory numerically. For which I am currently doing

$lastArchive = ls .\Archive | sort Name | select -Last 1
$dirName = '1'
if($lastArchive) {
  $dirName = ([int]$lastArchive.Name)+1
}

This of course fails once we get to 10 which by sorting rules follows after 1 not 9. I need the sort expression to actually be [int]$_.Name - how would I do this?

like image 408
George Mauer Avatar asked Jul 05 '12 23:07

George Mauer


People also ask

How do you sort objects in PowerShell?

Luckily, custom sorting is easy to accomplish in Windows PowerShell. To sort returned objects in Windows PowerShell, pipe the output from one cmdlet to the Sort-Object cmdlet. This technique is shown here where the Sort-Object cmdlet sorts the Process objects that are returned by the Get-Process cmdlet.

How do I sort in ascending order in PowerShell?

The Sort-Object cmdlet sorts objects in ascending or descending order based on object property values. If sort properties aren't included in a command, PowerShell uses default sort properties of the first input object.

How do I sort an array in PowerShell?

The first way to do this is to use the Sort-Object cmdlet (Sort is an alias for the Sort-Object cmdlet). The second way to sort an array is to use the static Sort method from the System. Array .

How do I sort a hash table in PowerShell?

To sort a hashtable, use the GetEnumerator() method on the hashtable to gain access to its individual elements. Then use the SortObject cmdlet to sort by Name or Value.


1 Answers

I think you need to change that first line as follows:

$lastArchive = ls .\Archive | 
               Sort-Object -property @{Expression={[int]$_.Name}} | 
               Select-Object -Last 1

Then, you can create the next directory in numerical order like this:

mkdir ([int]$lastArchive.Name + 1).ToString()
like image 164
David Avatar answered Sep 20 '22 17:09

David