【问题标题】:Open random file in a folder (and include exceptions) - in batch打开文件夹中的随机文件(并包括例外) - 批量
【发布时间】:2016-11-05 01:16:51
【问题描述】:

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

我还想添加“例外文件夹” - 随机打开的文件夹。

目前,我正在使用这个:

@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

它非常适合随机打开,但我不确定如何排除特定目录中的一些子文件夹。

提前感谢您的帮助! :)

【问题讨论】:

  • 将 robocopy 与 /L 和 /XD 开关一起用于您的编号列表

标签: batch-file random


【解决方案1】:

只是为了提供一个使用我在评论中给出的想法的解决方案;

@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%]%%"

【讨论】:

    【解决方案2】:
    for /f %%N in ('type "%tempFile%" ^| findstr /v /g:exclude_me_file.txt ^|find /c /v ""') do set cnt=%%N
    

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

    【讨论】:

    • 让我推荐一些更改:将/L 添加到findstr 以强制文字搜索字符串;添加/I 以不区分大小写搜索(就像Windows 也处理文件路径);排除文件中的每个目录前面都应该有一个反斜杠,并附加一个反斜杠,以免无意中匹配部分目录名称...
    猜你喜欢
    • 2018-12-31
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多