0

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.

1 Answer 1

2

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 using call echo %CD%, or by enabling delayed expansion with SETLOCAL EnableDelayedExpansion and using echo !CD!. But the simplest fix is to simply use cd; the CD command without any arguments will print the current directory to the screen.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.