Search code examples
windowsbatch-filemove

Windows batch script to find free file name


I have to write a script that will copy a file to a backup folder. If the file name is already taken, it will tack on an index. I can't seem to get it to work. The variable tmpfile never seems to carry the index counter. What am I doing wrong? The script is below.

Thanks, Sean

set srcdir=%~dp0
set oldxladir=%srcdir%OldXLAs

if not exist %oldxladir% mkdir %oldxladir%

set pathstart=C:\Documents and Settings\
set username=%USERNAME%
set pathend=\Application Data\Microsoft\Excel\XLSTART\
set pattern=groovy*.xla

set xladir=%pathstart%%username%%pathend%
set xlapattern="%pathstart%%username%%pathend%%pattern%"

for %%f in (%xlapattern%) do (
    set filename=%%~nxf
    set srcfile=%xladir%%filename%
    set destfile=%oldxladir%\%filename%
    set tmpfile=%destfile%

    set /a index=1
    :loop
    if exist tmpfile (
        set /a index+=1
        echo %index%
        set tmpfile=%destfile%%index%
        goto :loop
    )

    echo %tmpfile%
    move "%srcfile%" "%tmpfile%"
)

Solution

  • SETLOCAL ENABLEDELAYEDEXPANSION
    set srcdir=%~dp0
    set oldxladir=%srcdir%OldXLAs
    
    if not exist %oldxladir% mkdir %oldxladir%
    
    set pathstart=C:\Documents and Settings\
    set username=%USERNAME%
    set pathend=\Application Data\Microsoft\Excel\XLSTART\
    set pattern=groovy*.xla
    
    set xladir=%pathstart%%username%%pathend%
    set xlapattern="%pathstart%%username%%pathend%%pattern%"
    
    for %%f in (%xlapattern%) do (
        set filename=%%~nxf
        set srcfile=%xladir%!filename!
        set destfile=%oldxladir%\!filename!
        set tmpfile=!destfile!
    
        set /a index=1
        :loop
        if exist !tmpfile! (
            set /a index+=1
            echo !index!
            set tmpfile=!destfile!!index!
            goto :loop
        )
    
        echo !tmpfile!
        move "!srcfile!" "!tmpfile!"
    )