如何批量将文件从随机文件夹复制到目标文件夹?

时间:2012-12-27 17:48:04

标签: batch-file

我需要一个批处理脚本将文件从特定目录的随机子文件夹复制到目标目录。

例如,在它们自己的子目录中会有许多文件,例如

.../source/a/file.txt
.../source/b/file.txt

所以有很多这些文件,我想随机选择其中一个并将其复制到新目录中

.../destination/file.txt

因此,目标中的file.txt正在被其他具有相同名称但内容不同的文件覆盖。

我是批处理脚本的新手,我无法弄清楚如何从随机子文件夹中选择每个文件。我也希望它每30秒重复一次,直到我终止脚本,但我认为只要制作第二个脚本就可以每30秒调用一次.bat文件就足够了。

谢谢!

3 个答案:

答案 0 :(得分:0)

@echo off
setlocal EnableDelayedExpansion
rem Enter into the directory that contain the folders
pushd \Fullpath\source
rem Create an array with all folders
set i=0
for /D %%a in (*) do (
   set /A i+=1
   set folder[!i!]=%%a
)
rem Randomly select one folder
set /A index=(%random%*i)/32768 + 1
rem Copy the desired file
copy "!folder[%index%]!\file.txt" "\Fullpath\destination" /Y
rem And return to original directory
popd

答案 1 :(得分:0)

这可以满足您的要求。只需设置源目录,目标目录和文件名过滤器。

@echo off
setlocal EnableExtensions EnableDelayedExpansion

pushd "...\source\"

:: Enumerate Files. Method 1
set "xCount=0"
for /r %%A in (file.txt) do if exist "%%~A" set /a "xCount+=1"
echo %xCount%

:: Select a Random File.
set /a "xIndex=%Random% %% %xCount%"
echo %xIndex%

:: Find an Copy that File. Method 1
set "xTally=0"
for /r %%A in (file.txt) do if exist "%%~A" (
    if "!xTally!" EQU "%xIndex%" (
        xcopy "%%~fA" "...\destination\file.txt" /Y
        goto End
    )
    set /a "xTally+=1"
)

:End
popd
endlocal
pause

输入xcopy /?以查看其所有选项。

以下是文件枚举的一些备用循环方法。

:: Enumerate Files. Method 2
set "xCount=0"
for /f %%A in ('dir *.txt /a:-d /s ^| find "File(s)"') do set "xCount=%%~A"
echo %xCount%

:: Find an Copy that File. Method 2
set "xTally=0"
for /f "delims=" %%A in ('dir *.txt /a:-d /b /s') do (
    if "!xTally!" EQU "%xIndex%" (
        xcopy "%%~fA" "...\destination\file.txt" /Y
        goto End
    )
    set /a "xTally+=1"
)

享受:)

答案 2 :(得分:0)

批处理脚本的功能是

  1. 它将所有文件从源文件复制到具有相似结构的目标文件夹(甚至保留空文件夹)。
  2. 可以保留存档文件夹(源)中最近文件的N天数剩余文件将被移动到备份文件夹(目标)。
  3. 可以安排N天到N年。
  4. 可用于任何源到目标文件夹备份。
  5. 源文件夹可以随时添加N个文件夹并删除文件夹或文件,但目标文件夹始终会添加该文件夹,并且永远不会删除任何文件夹或文件。

    1. @echo off
    2. 设置“sourcefolder = E:\ Interfaces”
    3. 设置“destinationfolder = E:\ BackupInterface”

    4. 如果存在%sourcefolder%(

    5. For / F %% * In('Dir / b / aD“%sourcefolder%”2 ^> nul')do(如果不存在“%destinationfolder%\ %% ”(RD / S /问“%destinationfolder%\ %% ”)
    6. xcopy / e / v / i / y / q“%sourcefolder%\ %% ”“%destinationfolder%\ %%
    7. forfiles / p“%sourcefolder%\ %% *”/ s / d -30 / c“cmd / c del / Q / S @file”)

    8. )其他(无法找到echo.Source文件夹)

    9. :批次结束

    10. 回波&安培;!echo.finished