Open a random file from folder with Batch

2019-08-20 06:04发布

I'm an artist who is learning programming and I wanted to create a batch file that will select a random picture file from my references folder. The goal being to get a random picture to work on and study. I've looked around and the replies I see are hard to understand and are often linked with other features and functions I don't need. Simply put, how do I make a batch file that opens a random picture file from a folder (and subfolders)? Do I need to index every picture and then have a selector from that or can I just use %random% to open it?

Thank you for your help.

3条回答
Rolldiameter
2楼-- · 2019-08-20 06:50
@SETLOCAL ENABLEDELAYEDEXPANSION
rem @CD C:\newfolder
@set count=0
@For /f "delims=" %%A in ('dir C:\users\*.* /ad /s /b') Do (
@    set /a count=!count!+1
@rem     If !Count! gtr 1 echo Num of folders
)

@Set /a num=%random% %% %Count% + 1 
Echo %num% / %count%

For /f "skip=%num% delims=" %%A in ('dir C:\users\*.* /ad /s /b') Do (
Echo this is nth random folder
Echo Copy "%~dpnx0" "%%A"
rem Exit /b
)
pause

%Random% gives us a random number from 0 to 32K. @Set /a num=%random% %% %Count% + 1 uses modulo division (ie the remainder from a division) of 32K divided by how many will give us a random number in the range 0 to count. Then add 1 to make it 1 to count +1 (the number of folders). Then skip=%num% skips the first how ever many folders, reads the next, then exits the loop.

This is limited to 32K folders. See Dir /? for how to list files and files in subfolders. Every command above plus /? for help. See http://stackoverflow.com/questions/41030190/command-to-run-a-bat-file/41049135#41049135 for a CMD cheat sheet.

查看更多
唯我独甜
3楼-- · 2019-08-20 06:53

This is the basic batch file structure you'll need:

@Echo Off
Set "SrcDir=C:\Users\Jiosen\references"
Set "ExtLst=*.jpeg *.png *.tiff"
Set "i=0"
For /F "Delims=" %%A In ('Where /R "%SrcDir%" %ExtLst%') Do (Set /A i+=1
    Call Set "$[%%i%%]=%%A")
Set /A #=(%Random%%%i)+1
Call Start "" "%%$[%#%]%%"

You may need to adjust lines 2 and 3 as necessary, (but do not remove or add any doublequotes).

查看更多
ら.Afraid
4楼-- · 2019-08-20 06:56

PowerShell is more efficient in selecting files in a tree and getting a random file so why not use it from the batch.

Taking Compos batch as a template:

:: Q:\Test\2018\07\24\SO_51487674.cmd
@Echo Off
PushD "C:\Users\Jiosen\references"
Set "ExtLst=*.jpg,*.jpeg,*.png,*.tiff"

For /F "Delims=" %%A In ('
powershell -Nop -C "(Get-ChildItem * -R -File -Incl %ExtLst%|Get-Random).FullName"
') Do Start "" "%%A"

Get-ChildItem parameters -File,?-Include and Get-Random require at least PowerShell Version 3.0

According to the table in this link you need to upgrade Window 7 PowerShell v2 to at least V3, Windows 8 or higher should run the script without problem.
But I'd recommend to upgrade to 5.1 and possibly install PowerShell 6.0 (core) in parallel.

查看更多
登录 后发表回答