1

Good day! So I have this task that I have to accomplish in Batch due to heavy system restrictions.

The principle of it, it "randomly" selects files from a folder, and copies them to another folder. The problem is, sometimes the "randomness" selects the same file, thus out of 10 needed files, I end up with 8-9. I have tried to make a "validation" system, but I can't seem to make it work in a loop, so it kinda only does it once, and there is still a chance it will select the same file.

Sorry if the code is a complete spaghetti, im not a programmer

I have a feeling that the solution is really simple, and that i just dont see it Any kind of help, or advice is greatly appreciated Thank you in advance

"Validation" is in "sub3"

@echo off & setlocal enableextensions disabledelayedexpansion
set "workDir=C:\Generator\Tickets"
FOR /L %%n in (1,1,10) DO call :main %%n
goto :sub3

:main
@set /a "rdm=%random%"
set /a "rdm=%random%"
pushd "%workDir%"
set /a "counter=0"
for /f "delims=" %%i in ('dir /b ^|find "."') do call :sub1
set /a "rdNum=(%rdm%*%counter%/32767)+1"
set /a "counter=0"
for /f "delims=" %%i in ('dir /b ^|find "."') do set "fileName=%%i" &call :sub2
popd "%workDir%"
goto :eof
:sub1
set /a "counter+=1"
goto :eof
:sub2
set /a "counter+=1"
if %counter%==%rdNum% (
xcopy /y "C:\Generator\Tickets\"%fileName%"" "C:\Generator\temp"
)
goto :eof

:sub3
pushd "C:\Generator\temp" && (
        for /f "tokens=1,*" %%j in ('
            robocopy . . /l /nocopy /is /e /nfl /njh /njs
       ') do ( if %%j neq 10 goto main) 
        popd
    )
goto :eof
AudioTroubler
  • 69
  • 1
  • 1
  • 7
  • 1
    You might be interested in this thread: [How to generate a list of random numbers without duplicates in pure batch scripting?](http://stackoverflow.com/q/34406594) – aschipfl Mar 13 '17 at 18:21

1 Answers1

1

using a different logic:

@echo off
set "source=C:\Generator\Tickets"
set "dest=C:\Generator\temp"
REM make sure, destination is empty:
del /q "%dest%\*"
REM get number of files in source:
for /f %%a in ('dir /b /a-d "%source%\" ^|find /c /v ""') do set count=%%a
REM do ten times:
for /l %%a in (1,1,10) do call :sub
goto :eof

:sub
  REM get file index to copy [see 'set /?` for Modulo-operator]:
  set /a x=%random% %% %count% +1
  REM get filename of index:
  for /f "tokens=* skip=%x%" %%a in ('echo x^&dir /b /a-d') do set "file=%%a" & goto :cont
  :cont
  REM if file already exists in destination, try again:
  REM ATTENTION: this is an endless loop, if there are not enough files in source...
  if exist "%dest%\%file%" goto :sub
  REM else copy the file:
  copy "%source%\%file%" "%dest%\"
goto :eof
Stephan
  • 53,940
  • 10
  • 58
  • 91