Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I need a batch file:

Given folder A containing .txt files; e.g.,

C:\A\a.txt
C:\A\b.txt
C:\A\c.txt
C:\A\d.txt

and folder B (which is empty), I need the batch script to copy one randomly chosen file from folder A to folder B each time I run it.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Inspired by this post, your script could look like this

@echo off

setlocal enabledelayedexpansion

set source=c:\A
set target=c:\B

set count=0
set x=0

:: put all the files into a pseudo-array prefixed with "TXT_"
for /r "%source%" %%a in (*.txt) do (
    set TXT_!count!=%%~a
    set /a count+=1
)

:: Use the 'modulo' function to get a usable value from system variable %random%
set /a x="%random% %% count"

:: Pull the relevant item out of the "TXT_" 'array'
set chosen=!TXT_%x%!

echo:I chose :: %chosen%
copy /y "%chosen%" "%target%" 1>nul
endlocal

This assumes that you have a moderate number of files in your source folder. Otherwise, the number of variables in your environment might grow too big.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.