Batch contents:
FOR /F "tokens=1,*" %%i IN (list.txt) DO (
cd "%%j"
Echo %CD%
pause
)
Execution run:
C:\Dwn>tmp1.bat
C:\Dwn>FOR /F "tokens=1,*" %i IN (list.txt) DO (
cd "%j"
Echo C:\Dwn
pause
)
C:\Dwn>(
cd "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Administrative Tools"
Echo C:\Dwn
pause
)
The system cannot find the path specified.
C:\Dwn
Press any key to continue . . .
How come the system cannot find the path specified? If I copy that cd command and execute it by itself it works fine.
It fails because the value of %%j contains %APPDATA%. The value of %APPDATA% will not get expanded when you expand %%j because environment variable expansion occurs before FOR variable expansion.
The fix is to use
call cd "%%j"instead. The CALL will cause the command to go through an extra level of %VAR% expansion, which is exactly what you want.You also have a problem in that you use
echo %CD%within the same DO code block. It will echo the value of the current directory before your change because the value of %CD% is expanded when the entire FOR statement is parsed. You could fix this by usingcall echo %CD%, or by enabling delayed expansion withSETLOCAL EnableDelayedExpansionand usingecho !CD!. But the simplest fix is to simply usecd; the CD command without any arguments will print the current directory to the screen.