Reputation: 4405
I have read many questions and answers about pushd
here and on other sites, the overwhelming majority of them referring to issues with UNC paths. However, I've got a different problem I haven't seen a single hint about.
Using Windows 10 x64 Enterprise (Version 1809), I am executing the following batch file from within a console window:
@echo off
setLocal EnableDelayedExpansion
set DestDir=c:\windows
pushd %DestDir%
My problem is that pushd
seems to be executed in the wrong way or not at all. That means that I am not in c:\windows
when the batch file has been run, but still in the directory I was in before running it.
I have tried several things in a desperate attempt to understand the problem (knowing that those tests didn't make sense):
c:\windows
in quotes (set DestDir="c:\windows"
)%DestDir%
in quotes (pushd "%DestDir%"
)!
instead of %
because delayed expansion is on, i.e. pushd "!DestDir!"
However, when I do not turn on delayed expansion, pushd
works as expected. In other words, after having run the following batch file
@echo off
set DestDir=c:\windows
pushd %DestDir%
I indeed have been beamed into c:\windows
regardless of the directory I have been in before running the batch file.
I suppose that I am quite silly at the moment, but I can't wrap my head around this for the life of me. So could anybody please explain why pushd
fails if delayed expansion is active?
Upvotes: 3
Views: 2575
Reputation: 56180
The reason for your problem was already discussed in the comments, but there was no solution so far.
You can overcome the issue by an explicit endlocal
:
REM @echo off
setLocal EnableDelayedExpansion
set DestDir=c:\windows
endlocal & pushd %DestDir%
The last line is parsed in one go, so %DestDir%
is replaced to its value (before endlocal
) before executing the whole line (run with echo on
to watch).
Upvotes: 3