Zakir
Zakir

Reputation: 2382

Batch Script to get latest folder

I have to determine the latest release version from a release location containing release artifacts. Here is how the folder looks like:-

1.4
1.4.1
1.5
1.5.1
1.5.2
latest

In the above example my script should return 1.5.2. The release engineer creates a folder called latest and puts the latest release artifacts (1.5.2's contents in the above case) inside it - so I have a easy way to copy the latest release. But my problem is I want to print the version as well. here's my attempt:-

@echo off

SET Remote="\\path to release location"
SET newest=""

for /f %%a in ('dir %Remote% /b /od') do (if NOT %%a=="latest" SET newest=%%a)

echo %newest%

This works fine with the above example. But the release engineer sometimes creates a tmp or some other folder there (basically he forgets to clean up) and that screws up my naive assumption of filtering out just "latest". Is there a easy way to sort the folders that start with a number declare the newest release version.

Also pls suggest if there are any better idea of solving this

Upvotes: 1

Views: 2926

Answers (2)

Squashman
Squashman

Reputation: 14290

This does not rely on the newest modified date actually being the greatest release number.

@echo off
setlocal enabledelayedexpansion
set newest=000000000
PUSHD \\servername\share\directory
for /f "delims=" %%G in ('dir /b /ad ^| findstr /r "^[0-9][0-9]*\.[0-9][0-9]*"') do (
    FOR /F "tokens=1-3 delims=." %%H IN ("%%~G") DO (
        SET "node1=000%%H"
        SET "node1=!node1:~-3!"
        SET "node2=000%%I"
        SET "node2=!node2:~-3!"
        SET "node3=000%%J"
        SET "node3=!node3:~-3!"
        IF 1!node1!!node2!!node3! GTR 1!newest! (
            set newest=!node1!!node2!!node3!
            set newrelease=%%G
        )
    )
)
echo %newrelease%
POPD
pause

Upvotes: 1

Zakir
Zakir

Reputation: 2382

Posting the solution here as per @Squashman's suggestion:-

@echo off

SET Remote="//Path to release loc"
SET newest=not set

for /f %%a in ('dir %Remote% /b /on  ^| findstr /r "^[0-9][0-9]*\.[0-9][0-9]*"') do (SET newest=%%a)

echo %newest%

Note:- The sort order /od vs /on is something I have to work with the release engineer to agree upon to protect against situations like: patching an older release does not over-write the latest release

Thanks everyone!!

Upvotes: 1

Related Questions