Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: choose folder by version number

Tags:

powershell

I'm writing a PowerShell script that goes into a couple of folders and runs a .bat file inside said folders. These folders are frequently updated and I only need to run the script from the newest folder of a certain type.

The folders look something like this:

Core_1.1.2
Core_1.3.4
Core_1.4.1
Extras_1.0.4
Extras_1.2.5
Extras_1.3.8
etc_1.1.2
etc_1.1.9
etc_1.2.6

Using the above folders as an example, I would need to go into Core_1.4.1, Extras_1.3.8, and etc_1.2.6 and run a file called run.bat which exists in each one of those directories.

So what I would need is to find the highest version in Core_*, the highest version in Extras_*, etc.

If there was some way to get an array of folder names with a specific prefix, then sort the elements of that array alphanumerically and return the last item in the array that would work perfectly. I'd like to stay away from choosing folder based on modification dates as that might be problematic.

like image 907
George Kendros Avatar asked Mar 18 '23 14:03

George Kendros


2 Answers

There is a System.Version class which can help do the parsing and sorting for you. This solves problems caused by comparing strings. Comparing strings will result in lexicographic sorts where 1.10.0 is "lower" than 1.2.0. This not the typical order used when comparing version numbers. Something like this could work to find the newest "Core" folders:

$core = ls -Filter Core_* | sort { [version]($_.Name -replace '^.*_(\d+(\.\d+){1,3})$', '$1') } -Descending | select -Index 0

Then it just a matter of calling the bat file:

 & "$($core.FullName)\activate.bat"
like image 199
Mike Zboray Avatar answered Mar 23 '23 13:03

Mike Zboray


My first idea would be something like this:

$versions = { [int]($_.Name -replace '.*?_(\d+)\.(\d+)\.(\d+)', '$1') }, { [int]($_.Name -replace '.*?_(\d+)\.(\d+)\.(\d+)', '$2') }, { [int]($_.Name -replace '.*?_(\d+)\.(\d+)\.(\d+)', '$3') }

#Get folders
Get-ChildItem |
#Extract versions and sort highest first
Sort-Object $versions -Descending |
#Get first item/folder (highest version)
Select-Object -First 1


    Directory: C:\Users\Frode\Desktop\test


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        29.08.2014     18:43            Core_1.4.1  
like image 38
Frode F. Avatar answered Mar 23 '23 15:03

Frode F.