【问题标题】:Trying to create a batch file to select one random file from a folder and copy to another folder尝试创建批处理文件以从文件夹中选择一个随机文件并复制到另一个文件夹
【发布时间】:2017-09-13 22:28:21
【问题描述】:

对批处理编码非常陌生,我有一个包含 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

【问题讨论】:

  • cd /D "E:\New folder"copy "!file[%rand%]!" "E:\samples\New folder"...

标签: batch-file


【解决方案1】:

变化:

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

并且,正如 cmets 中所建议的,替换

是个好主意

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

如另一条评论中所述,将相应的行更改为:

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

【讨论】:

  • 它运行良好,但给了我提到的“错误”消息
  • 嗯? batch 文件默认是可执行的。什么“标题”? batch 没有这样的东西。
  • 好的,使 cd "E:\New folder" 或 cd "E:\\New folder" 更改有效,现在我看到我必须定义代码以仅复制图像文件(jpeg, jpg等)我应该把它放在哪里以及如何?
  • 然后呢?关于缺少路径的错误消息?
  • @Amos:将for %%f in (*.*) do ( 替换为for %%f in (*.jpeg *.jpg) do (。需要时添加更多扩展。
【解决方案2】:
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
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-02
    • 2014-03-21
    • 2011-07-29
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多