Windows批处理脚本查找免费文件名

时间:2013-10-01 13:15:32

标签: windows batch-file move

我必须编写一个将文件复制到备份文件夹的脚本。如果已经采用了文件名,它将在索引上添加。我似乎无法让它发挥作用。变量tmpfile似乎永远不会带有索引计数器。我究竟做错了什么?脚本如下。

谢谢, 肖恩

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%"
)

1 个答案:

答案 0 :(得分:2)

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!"
)