Ran into an interesting problem today - a PowerShell script I’ve been using for deploying new releases into test environments started misbehaving.

Turned out the problem related to the folder names being used - our version numbers had just clicked over pass 999 and the wrong release was being pushed out.

A partial directory listing of the releases folder shows the problem clearly - note how the 1004 build doesn’t appear at the bottom of the list.

d----   14/11/2012 3:53 p.m.        <DIR> Release 4.5.982.0
d----   15/11/2012 9:44 a.m.        <DIR> Release 4.5.983.0
d----   19/11/2012 1:37 p.m.        <DIR> Release 4.5.986.0
d----   28/11/2012 9:49 a.m.        <DIR> Release 4.5.992.0
d----   14/12/2012 3:36 p.m.        <DIR> Release 4.6.1004.0
d----   27/11/2012 2:32 p.m.        <DIR> Release 4.6.988.0
d----  29/11/2012 11:35 a.m.        <DIR> Release 4.6.994.0
d----   4/12/2012 10:14 a.m.        <DIR> Release 4.6.996.0
d----    4/12/2012 4:04 p.m.        <DIR> Release 4.6.997.0

Most of you have probably already diagnosed the problem - an alphabetical ordering has been used instead of a numerical one.

The line of powershell looked like this:

    $allReleases = get-item "$archiveDir\Release *" 

After a brief consultation with Professor Google, I found an interesting post on sorting version numbers.

The key trick is that Powershell allows very simple casting from string values, coupled with the support of the Version class for comparisons.

Here’s the updated line of code:

    $allReleases = ( get-item "$archiveDir\Release *" 
        | sort-object -Property @{ e={ [Version]($_.Name.Split(" ")[1]) } } )

And here’s how it works.

  • sort-object does the sorting, based on a script block that provides a key for each folder

  • $_.Name returns the name of each folder

  • .Split(" ")[1] divides the name into two parts (either side of the space) and selects the later

  • [Version] converts the string into an instance of the version class, which is used for sorting.

With this result:

d----   14/11/2012 3:53 p.m.        <DIR> Release 4.5.982.0
d----   15/11/2012 9:44 a.m.        <DIR> Release 4.5.983.0
d----   19/11/2012 1:37 p.m.        <DIR> Release 4.5.986.0
d----   28/11/2012 9:49 a.m.        <DIR> Release 4.5.992.0
d----   27/11/2012 2:32 p.m.        <DIR> Release 4.6.988.0
d----  29/11/2012 11:35 a.m.        <DIR> Release 4.6.994.0
d----   4/12/2012 10:14 a.m.        <DIR> Release 4.6.996.0
d----    4/12/2012 4:04 p.m.        <DIR> Release 4.6.997.0
d----   14/12/2012 3:36 p.m.        <DIR> Release 4.6.1004.0

Sweet!

Comments

blog comments powered by Disqus