The purpose is to select a single folder at random from within a given text file containing a folder list using a batch script in Windows.
Step by step method:
- input home directory path
- check current drive letter and change drive letter to match homedir drive if necessary
- change directory to home directory
- write dir list to text file HOMEDIR.TXT in home directory
- set
SKIP
variable to a random number up to the number of lines in that text file EVERYTHING WORKS UP TO THIS POINT - For loop with no delimiters (so I get the whole line) and skip
%SKIP%
number of lines. Then do set VARNAME=%%I from the for loop. Then goto NextLine so it's not repeated until the end of the text file. ***THIS STEP GIVES ME ERROR: System cannot find file specified.
[EDIT] On further testing, error only happens IF %SKIP% > 4 i.e. if SKIP corresponds to a line with a filepath on it, it gives that error. Else it works fine.
I've read all the answers everywhere, but can't solve it! If I take the for outside into a test file with just random words it works fine. So I can only presume it's something to do with the special characters in the dir output list that are causing problems? Any help much appreciated!
My Code:
:: 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