在批处理中打开文件夹中的随机文件(并包含例外)

时间:2016-11-04 16:11:54

标签: batch-file random

我想创建一个批处理文件,用于在文件夹及其所有子文件夹中打开随机文件。

我还想添加“例外文件夹” - 文件夹,从随机开放中排除。

目前,我正在使用它:

@echo off
setlocal

:: Create numbered list of files in a temporary file
set "tempFile=%temp%\%~nx0_fileList_%time::=.%.txt"
dir /b /s /a-d %1 | findstr /n "^" >"%tempFile%"

:: Count the files
for /f %%N in ('type "%tempFile%" ^| find /c /v ""') do set cnt=%%N

call :openRandomFile

:: Delete the temp file
del "%tempFile%"

exit /b

:openRandomFile
set /a "randomNum=(%random% %% cnt) + 1"
for /f "tokens=1* delims=:" %%A in (
  'findstr "^%randomNum%:" "%tempFile%"'
) do start "" "%%B"
exit /b

它适用于随机打开,但我不确定如何排除特定目录中的某些子文件夹。

提前感谢您的帮助! :)

2 个答案:

答案 0 :(得分:2)

提供一个解决方案,使用我在评论中提出的想法;

@Echo Off

(Set SrcDir=C:\Users\teapuppets\Documents)
(Set ToExcl=mortgage invoices)

Set "i=0"
For /F "Tokens=*" %%A In (
    'Robocopy "%SrcDir%" NULL /L /S /FP /NDL /NS /NC /NJH /NJS /XD %ToExcl%'
    ) Do (Set/A i+=1
    Call Set File[%%i%%]=%%A)

Set/A "RndNum=(%random% %% i) + 1"
Call Start "" "%%File[%RndNum%]%%"

答案 1 :(得分:0)

for /f %%N in ('type "%tempFile%" ^| findstr /v /g:exclude_me_file.txt ^|find /c /v ""') do set cnt=%%N

exclude_me_file.txt包含要排除的目录,其中一个包含一行