尝试创建批处理文件以从文件夹中选择一个随机文件并复制到另一个文件夹

时间:2017-04-18 07:26:36

标签: batch-file

批处理编码非常新,我有一个包含1000多个子文件夹的文件夹,我正在尝试使用以下内容将每个子文件夹中的一个文件复制到一个新文件夹中。 两个文件夹都已创建。 所有都在外部高清 如果相关,所有文件都是JPEG。 执行时(从资源管理器中双击)获取:“系统找不到指定的路径”批处理文件错误 请帮忙: - (

@echo off
setlocal EnableDelayedExpansion
cd E:\"New folder"
set t=0
for /d %%i in (*) do (
    cd "%%i"
    set /A t+=1
    set n[!t!]=0
    for %%f in (*.*) do (
       set /A n[!t!]+=1
       set "file[!n!]=%%f"
    )
    set /A "rand=(n[!t!]*%random%)/32768+1"
    copy "!file[%rand%]!" E:\samples\"New folder"
    cd..
)
pause

2 个答案:

答案 0 :(得分:0)

更改:

cd E:\"New folder"cd "E:\New folder" or cd "E:\\New folder"

并且,正如评论中所建议的那样,替换

是个好主意 带有for %%f in (*.*) do (

for %%f in (*.jpeg *.jpg) do (

正如另一条评论中所述,也改变了适当的行:

copy "!file[%rand%]!" "E:\samples\New folder"

答案 1 :(得分:0)

for /d %%i in (*) do (
    cd "%%i"
    ^^^^^^^ Perhaps you should use "PUSHD" here
    set /A t+=1
    set n[!t!]=0
    ^^^ This set n[1], n[2] etc to 0; increment each directory
    for %%f in (*.*) do (
       set /A n[!t!]+=1
       ^^^^ Increment filecount in each directory
       set "file[!n!]=%%f"
       ^^^^ This will set a variable called "file[]" to the filename
       ^^^^ since n is undefined. n[!t!] is defined; n is not
    )
    set /A "rand=(n[!t!]*%random%)/32768+1"
    ^^ OK - this sets "rand" to a random number.
    ^^ Personally, I'd use "!random!" since that will change for every
    ^^ iteration of %%i. As it stands, it will be replaced by the value
    ^^ of RANDOM at the time "for...%%i..." is parsed, consequently if 2
    ^^ directories have the same number of files and remain unchanged
    ^^ between runs, then the same 2 files will be "paired" on extraction
    ^^ Better in my book is SET /a rand=!random! %% n[!t!] +1
    copy "!file[%rand%]!" E:\samples\"New folder"
    ^^ Well, "file[]" would be selected here as "rand" is not set when 
    ^^ "for...%%i..." is parsed
    cd..
    ^^^^ and "POPD" here
)