Solved Get the name of the random file in the folder

March 11, 2019 at 08:37:30
Specs: Windows 7
I have 1 folder of files
a.xls
b.doc
c.docx
e.xls
f.text
...
Now I want to randomly name 1 of the files in that folder and save it in a file random.txt how do I do it?
Looking forward to your help. Sincere thanks!

See More: Get the name of the random file in the folder

Reply ↓  Report •

#1
March 11, 2019 at 10:53:53
✔ Best Answer
Place test.bat in the folder you want a name from.
This generates a test-results.txt file on the desktop with the chosen random name(removes file extention, but can be changed if you want), this "test-results.txt" is overwritten every time you run test.bat

code:


@echo off&setlocal enabledelayedexpansion
pushd "%~dp0"
set cnt=0
for /f "tokens=1,2 delims=." %%a in ('dir/b/A-D') do if not "%%a"=="%~n0" set/a cnt+=1
set/a usethisnumber=(%random%+1)/!cnt!
set ans=0
for /f "tokens=1,2 delims=." %%a in ('dir/b/A-D') do (
if not "%%a"=="%~n0" (
set file=%%a
set/a ans+=!usethisnumber!
if !ans! GEQ %random% goto result
)
)
:result
echo !file!>%USERPROFILE%\DESKTOP\%~nx0-result.txt

i5-6600K[delid]@4.8GHz/4.4GHz cache/@1.408v | 2x4GB Crucial-DDR4-2400CL17@14-15-15-28 1T 3000MHz@1.4v | Sapphire Nitro+ SE RX 590 8GB@1525Mhz core@1.0v/2260MHz@1500MHz timings BiosModded

message edited by hidde663


Reply ↓  Report •

#2
March 11, 2019 at 10:57:43
simply change:

set file=%%a
to
set file=%%a.%%b

if you want the fileextension to also go into test-results.txt

i5-6600K[delid]@4.8GHz/4.4GHz cache/@1.408v | 2x4GB Crucial-DDR4-2400CL17@14-15-15-28 1T 3000MHz@1.4v | Sapphire Nitro+ SE RX 590 8GB@1525Mhz core@1.0v/2260MHz@1500MHz timings BiosModded


Reply ↓  Report •

#3
March 11, 2019 at 18:44:23
Just throwing this out there, but:
FOR /F %%a IN ('DIR /A-D ^| FIND "File(s)"') DO SET /A rnd=%random% %% %%a + 1
FOR /F "tokens=1* delims=:" %%a IN ('DIR /A-D /B ^| FINDSTR /N "." ^| FIND "%rnd%:"') DO @ECHO %%b

How To Ask Questions The Smart Way

message edited by Razor2.3


Reply ↓  Report •

Related Solutions

#4
March 11, 2019 at 19:54:51
This is a similar answer to my question:
@echo off
setlocal EnableDelayedExpansion
cd e:\question
set n=0
for %%f in (*) do (
set /A n+=1
set "file[!n!]=%%f"
)
for /L %%i in (1,1,%time:~-1%) do set "dummy=!random!"
set /A "rand=(n*%random%)/32768+1"
echo "!file[%rand%]!">%USERPROFILE%\DESKTOP\%~nx0-result.txt

Thank you very much for your help.


Reply ↓  Report •

Ask Question