目的是在Windows中使用批處理腳本在給定文本文件中隨機選擇一個包含文件夾列表的文件夾。從文本文件中的dir列表讀取文件路徑並將其作爲變量存儲在批處理腳本中Windows
循序漸進的方法:
- 輸入主目錄路徑
- 檢查當前驅動器號和更改驅動器號,以匹配主目錄驅動器,如果有必要
- 目錄更改到主目錄
- 寫目錄列表到主文件夾中的文本文件HOMEDIR.TXT
- 設置
SKIP
變量爲一個隨機數,直到該文本文件中的行數 一切正常了這一點 - 對於無定界符環(所以我得到的整條生產線),並跳過
%SKIP%
行數。然後從for循環設置VARNAME = %% I。然後轉到NextLine,所以它不會重複,直到文本文件的結尾。 ***此步驟給我錯誤:系統找不到指定的文件。
[編輯]在進一步的測試,錯誤僅發生IF%SKIP%> 4即,如果跳過對應於與在其上的文件路徑的線,它給出了錯誤。否則它工作正常。
我已經閱讀過所有的答案,但無法解決它!如果我將外部文件帶入隨機單詞的測試文件,它可以正常工作。所以我只能假設這是與導致問題的dir輸出列表中的特殊字符有關?任何幫助非常感謝!
我的代碼:
:: Make the code run quietly
@ECHO OFF
:: Get home directory
set HOMEDIR=D:\External\My Pictures
:: Switch to the drive of HOMEDIR
:: If the drive letter of the current directory differs from HOMEDIR
:: Then change drive letter
:: Else change directory to root of that drive
:: Thanks Jatrim for if not http://stackoverflow.com/questions/1421441/batch-not-equal-operator
if not %cd:~0,2% == %HOMEDIR:~0,2% %HOMEDIR:~0,2% else cd %HOMEDIR:~0,2%
:: Change directory to HOMEDIR
cd "%HOMEDIR%"
:: Write a list of the subdirectories of HOMEDIR to file homedir.txt
dir "%cd%" /a:d >> homedir.txt
:: Calculate how many lines there are in homedir.txt
:: Thanks Aacini from http://stackoverflow.com/questions/13343144/random-line-of-text-ussing-batch
for /F "" %%I in (homedir.txt) do set /a LINES=%%I
echo LINES=%LINES%
:: enable delayed expansion (needed???)
setlocal EnableDelayedExpansion
:: Set a random integer (within the limit of variable LINES)
:: Thanks Aacini from http://stackoverflow.com/questions/13343144/random-line-of-text-ussing-batch
set /a SKIP=%random%%%LINES%
echo SKIP=%SKIP%
:: In homedir.txt the first 5 lines aren't directories
:: SKIP THESE LINES SOMEHOW
:: Thanks Andriy M for the inspiration! http://stackoverflow.com/questions/6409869/echo-the-nth-line-from-a-text-file-where-n-is-a-command-line-argument
:: If it's the same as SKIP, read line's contents into variable SCRDIR
for /F "usebackq delims= skip=%SKIP%" %%I in (homedir.txt) do (if not defined SCRDIRORIG set SCRDIRORIG=%%I & GoTo :NextLine)
pause
:NextLine
echo %SCRDIRORIG%
pause
哇感謝Endoro!你的代碼是一個夢想:D 我唯一的問題是我不明白它......特別是「。%%〜a。= %%〜b」?我敢肯定,你可以看到我的代碼級別與你的代碼級別相去甚遠......我以前從來沒有用過findstr,也沒有使用過$操作符 - 但我確信我能弄清楚這些。這是。和〜「在for循環中與」「相結合,這將使我永遠呆在谷歌;) – jfgoodhew1