复制随机文件夹即将停止

时间:2013-10-24 10:11:40

标签: batch-file random copy directory

我正在创建一个脚本,将随机文件夹从源复制到目标,直到该文件夹​​已满(知道目标文件夹小于源文件。

所有单个部分都按预期工作,但我现在正在运行脚本而不包含副本(只是一个回声)所以基本上如果没有任何文件夹大于目标目录中的剩余空间,它应该永远奔跑。

但它平均停止5次迭代,而没有任何文件夹足以填满目录。这是我正在使用的代码

编辑:得到它几乎工作,但现在有时候need_space输出0

@ECHO off
setlocal EnableDelayedExpansion

SET n=0
SET SOURCE_PATH=M:\Movies
SET DEST_PATH=E:\Movies

:: get all folders in dir
FOR /f "usebackq tokens=*" %%a in (`DIR /b/a:d %SOURCE_PATH%`) do (
    SET /A n+=1     
    SET folder[!n!]=%%a
)


:loop
    :: selecting ranodm number
    SET /A rand=(n*%random%)/32768+1

    :: check for space
    for /F "tokens=3" %%S in ('dir /-c "%SOURCE_PATH%\!folder[%rand%]!\*" ^| findstr /c:"File(s)"') DO set NEEDED_SPACE=%%S
    FOR /f "tokens=1*delims=:" %%i IN ('fsutil volume diskfree %DEST_PATH%') DO SET FREE_SPACE=%%j

    ECHO %FREE_SPACE% - %NEEDED_SPACE%
    IF %NEEDED_SPACE% GTR %FREE_SPACE% GOTO done

    :: check if file does not exits
    IF EXIST %DEST_PATH%\!folder[%rand%]! GOTO loop 

    :: copy file
    ECHO moving %SOURCE_PATH%\!folder[%rand%]! to %DEST_PATH%\!folder[%rand%]!

    :: again
    GOTO loop

:done
    ECHO Done copying random folders, have fun!

2 个答案:

答案 0 :(得分:2)

1.-你没有考虑到环境空间的耗尽。也许你无法创建你想要的数组。

2.- fsutil volume diskfree ...始终返回VOLUME中的空格,无论您是否指明目录

3 .- if命令仅在运算符两侧的所有字符都是数字时才进行数字比较。你的()禁用它,所以(10)小于(3)

答案 1 :(得分:0)

好的,到目前为止这是有效的。等待磁盘充满,如果有效,这应该足够了(不是100%完美检查,但足够接近)

代码:

@ECHO off
setlocal EnableDelayedExpansion

SET n=0
SET SOURCE_PATH=M:\src
SET DEST_PATH=E:\dest

:: get all folders in dir
FOR /f "usebackq tokens=*" %%a in (`DIR /b/a:d %SOURCE_PATH%`) do (
    SET /A n+=1     
    SET folder[!n!]=%%a
)

:loop
    :: selecting ranodm number
    SET /A rand=(n*%random%)/32768+1

    :: check for space
    for /F "tokens=3" %%a in ('dir /-c "%SOURCE_PATH%\!folder[%rand%]!" ^| findstr /c:"File(s)"') do set bytesfree=%%a
    set bytesfree=%bytesfree:,=%
    set /a NEEDED_SPACE=%bytesfree:~0,-3%

    for /f "tokens=3" %%a in ('dir %DEST_PATH%\') do set bytesfree=%%a
    set bytesfree=%bytesfree:,=%
    set /a FREE_SPACE=%bytesfree:~0,-3%


    ECHO %FREE_SPACE% - %NEEDED_SPACE%
    IF %NEEDED_SPACE% GTR %FREE_SPACE% GOTO done

    :: check if file does not exits
    IF EXIST %DEST_PATH%\!folder[%rand%]! GOTO loop 

    :: copy file
    set src="%SOURCE_PATH%\!folder[%rand%]!\*"
    set dest= "%DEST_PATH%\!folder[%rand%]!\*"
    ECHO moving %src% to %dest%
    xcopy /s /e /i %src% %dest%

    :: again
    GOTO loop

:done
    ECHO Done copying random folders, have fun!