Özenç B.
Özenç B.

Reputation: 1038

Opening a random folder from a set directory

How can I create a batch script that opens a random folder within a specific directory? This code here prints out a randomly chosen file(I need it to open the folder, not the file) but I could not figure out how to open it.

@Echo Off

:Start
set directory="D:\Movies"
set count=0
for /f %%f in ('dir "%directory%" /b /s') do set /a count+=1
set /a randN=%random% %% %count% +1
set listN=0

for /f "tokens=1* delims=:" %%I in ('dir "%directory%" /a-d /b /s^| findstr /n /r . ^| findstr /b "%randN%"') do set filename=%%J

:Found
echo %filename%
pause
goto Start

I suddenly realised what I was doing wrong and solved the problem. Here is the final and working code:

@Echo Off

:Start
set directory="D:\Film"
set count=0
for /f %%f in ('dir "%directory%" /ad /b /s') do set /a count+=1
set /a randN=%random% %% %count% +1
set listN=0

for /f "tokens=1* delims=:" %%I in ('dir "%directory%" /ad /b /s^| findstr /n /r . ^| findstr /b "%randN%"') do set filename=%%J

:Found
%SystemRoot%\explorer.exe %filename%
exit /b

goto Start

Upvotes: 0

Views: 460

Answers (1)

Compo
Compo

Reputation: 38614

You really shouldn't need to increment a count and use findstr for such a task; just assigning and sorting a random number should do:

@Echo Off
Set "source=D:\Film"

SetLocal EnableDelayedExpansion
For /D %%A In ("%source%\*") Do Set "$[!RANDOM!]=%%A"
For /F "Tokens=1* Delims==" %%A In ('"Set $[ 2>Nul|Sort"'
) Do Set "target=%%B" & GoTo Found
Exit /B

:Found
Explorer "%target%"

If you wanted a recursive directory search then change line 5 to:

For /D /R "%source%" %%A In (*) Do Set "$[!RANDOM!]=%%A"

Upvotes: 1

Related Questions