Search code examples
windowsbatch-filecommand-lineconditional-statementsxcopy

Find folder named with lowest number in a directory , conditional statement on the command line


I'm new to conditional statements with the command lein, I'd like to write a batch file for a server running Windows Server 2003 to do a similar task as this, but for the statement to find the lowest numbered folder (including subdirectories) and copy that to an external drive attached to the server.

Suppose if have folders with names like 9, 10, 11,... up to 1023. I guess the command to copy the folder (once determined and found) would look something like:

xcopy source:\dir\subdir\9 destination:\dir\subdir\9 /s /e /t

Basically, there's a large number of files added to the drive daily and this has to be moved to an archive on the external monthly. How would I go about writing an if statement for finding the folder named of the lowest number?


Solution

  • I don't understand what the lowest numbered folder has to do with the recently added files, but I'll assume you know what you are doing.

    You imply you want to copy the recently added files, so you don't want the XCOPY /T option. I've added the /I option so that XCOPY assumes your destination is a folder.

    The logic for identifying the lowest folder is simple:

    1) set low to the highest possible number in batch (I used hex notation)

    2) list all directories, using FINDSTR to restrict the list to integer names

    3) process the list with FOR /F. For each folder, test if it is lower than the current low value. If so, assign the folder to low.

    @echo off
    setlocal enableDelayedExpansion
    
    :: Establish source and destination folders
    set "src=c:\dir\subdir"
    set "dest=d:\dir\subdir"
    
    :: Identify the lowest folder
    set /a low=0x7fffffff
    for /f %%A in ('dir /b /ad "%src%"^|findstr /x [0-9]*') do if %%A lss !low! set "low=%%A"
    
    :: Copy the lowest folder
    xcopy "%src%\%low%" "%dest%\%low%" /s /e /i