why is my cd %myVar% being ignored?

1. Quoting unknown paths

Paths not known on running a batch file and not being fixed could contain 1 or more spaces. This means path strings should be quoted like file names.

2. Change drive and directory

Command CD changes by default the current directory on current drive only.

Option /D to change current directory to a directory on any drive with a letter should be always used when current directory on starting a batch file is not fixed on same drive as temporarily used current directory.

3. setlocal and endlocal save and restore also current directory

The command setlocal creates always a new copy of the environment table which is destroyed when using endlocal or exiting the batch file restoring previous table. Also the states of command extensions and delayed expansion is saved and restored. See this answer with an example demonstrating what happens on using setlocal and endlocal.

But additionally setlocal saves also current directory and endlocal restores it as the following code demonstrates.

@echo off
set "InitialPath=%CD%"
echo 1. Current directory is: %CD%
cd /D "%windir%\Temp"
echo 2. Current directory is: %CD%
setlocal
rem Change current directory to parent directory.
cd ..\
echo 3. Current directory is: %CD%
setlocal
rem Change current directory to root of current drive.
cd \
echo 4. Current directory is: %CD%
endlocal
echo 5. Current directory is: %CD%
endlocal
echo 6. Current directory is: %CD%
cd /D "%InitialPath%"
echo 7. Current directory is: %CD%
set "InitialPath="
pause

4. Trailing spaces and tabs assigned to environment variable

With not using double quotes on assigning a value to an environment variable, command set appends everything after first equal sign up to end of line to the environment variable including not visible trailing spaces and tabs. There are trailing spaces on line set originalPath=%~dp0  , see answer on Why is no string output with ‘echo %var%’ after using ‘set var = text’ on command line? for more details.


Your code improved to avoid all the possible issues listed above:

@echo off
set "myPath=Subfolder1"
set "folderList=input.txt"
REM set "originalPath=%CD%"
set "originalPath=%~dp0"

REM pushd "%myPath%"
cd /D "%myPath%"
setlocal EnableDelayedExpansion

:process
REM The rest of my script

endlocal
echo %originalPath%
REM echo %originalPath% prints: C:\BatchTests\
cd /D "%originalPath%"
REM popd
pause

And taking point 3 into account and as aschipfl also explained well, following would work, too.

@echo off
set "myPath=Subfolder1"
set "folderList=input.txt"

setlocal EnableDelayedExpansion
cd /D "%myPath%"

:process
REM The rest of my script

endlocal
pause

Leave a Comment