2

I need to create a batch file for Windows OS that will select a random file from a particular folder, then copy that file to a different folder. I still need a copy of that file to remain in the original location.

FYI, it needs to be a batch file.

Thanks in advance for your help...

Cheri
  • 31
  • 1
  • 1
  • 4
  • Batch file for what kind of operating system? Windows, linuxes (+unix) and OS X have different languages to implements such functionality. – рüффп Sep 22 '13 at 16:00
  • Windows... sorry that I didn't specify this from the beginning. I will edit the question to reflect the operating system. – Cheri Sep 22 '13 at 18:18
  • @Cheri: That is not necessary; the `batch-file` tag clearly indicate: "Script files containing a series of commands that are executed by the Windows command-line interpreter". – Aacini Sep 22 '13 at 18:25
  • Okay, I will accept it... just testing it out first. – Cheri Sep 22 '13 at 21:57

2 Answers2

6
@echo off
setlocal EnableDelayedExpansion
cd \particular\folder
set n=0
for %%f in (*.*) do (
   set /A n+=1
   set "file[!n!]=%%f"
)
set /A "rand=(n*%random%)/32768+1"
copy "!file[%rand%]!" \different\folder
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • Just to be clear, I just copy this entire code and replace the file paths, correct? – Cheri Sep 22 '13 at 18:21
  • "access is denied" :( – john k Sep 24 '20 at 15:05
  • Xcopy worked where copy didn't. I just had to add the /Y /I switches – john k Sep 24 '20 at 15:29
  • I would need some information: how do I make sure the batch keep generating random numbers? – Les Go Feb 18 '21 at 11:56
  • The code above was giving me the same random number on each run. (Windows 11) I changed the following line which fixed the problem, from: `set /A "rand=(n*%random%)/32768+1"` to `set /A "rand=%random% %% n + 1"` – rossnixon Dec 24 '22 at 01:16
1
@echo off
set/a %%/folder
/a copy <folder2>
Zoe
  • 27,060
  • 21
  • 118
  • 148