PowerShell v2 Sort Folders by Name as Versions Objects

Working with developers can pose challenges at times. In their world objects are just obvious, intuitive structures you are expected to deal with. Ok. No problem. Adapt = survive. I can live with that. So, sometimes the laissez faire attitude of adaptation can be fun. In this case, I needed to find the last two build folders in a directory.  So, for non-developer types the System.Version class gives you an easy way to pattern Visual Studio builds incrementally without any effort.  Ok. I can work with that.

Where it gets cool, in my case, is that you can compare Version objects. Here is a post talking about the basics of that operation:
PowerShell: Comparing Version numbers
Cool enough. But, I did not want to build my own sort algorithm to work with custom object types for a simple folder sort. I looked at appending a Version object as a property with Add-Member via PowerShell, but, that didnt go very far anyway. Windows, when you parse the name as a Version object, still uses the Explorer sorting. So, that didnt get me any closer to a solution.

Fine, back to the drawing board. Finally, I stumbled onto using custom blocks with Sort-Object to craft what I needed
Sort using a custom comparator
After reading through the help a little more carefully I came up with this:
if(-not(Test-Path C: est))
{
      md C: est | Out-Null
}
else
{
      Set-Location C: est
      1..2 | % {
            $outer = $_; 1..5 |
            % {
                  if(-not(Test-Path "C: est1.1.$($outer).$($_)"))
                  {
                        md "C: est1.1.$($outer).$($_)" | Out-Null
                  }
            }
      }
}

Start-Sleep 2

Get-ChildItem C: est |
Where-Object {$_.Name -as [Version]} |
Sort-Object -Property @{e={[Version] $_.name};Ascending=$true} |
Select-Object -last 2
The key line here is
 Sort-Object -Property @{e={[Version$_.name};Ascending=$true}
What it does is casts the folder name to a Version object and sorts against this property. So, this way, you can actually do the sorting with the type implied by the cast. Very cool.

Related Posts by Categories

0 comments:

Post a Comment