Temporarily change directory for single batch-file command

In shell-scripting if I need to run a command from a directory I can us a subshell to ensure I return to the original context:

(cd temporary/new/directory ; command)
# now I am still in original directory

Can this be done in Windows batch-files (or cmd-files)

Doing the same in batch-files leaves me in the new directory.

I can do:

pushd temporary\new\directory && command && popd

But the popd is dependent on the success of command.

Any ideas?


Solution 1:

If you do:

pushd \windows && foobar && popd

you'll be left (as you state) in the \windows folder. Try:

pushd \windows & foobar & popd

and you should find yourself back where you started.

Solution 2:

By default, Windows batch files are run in the parent shell's context (which is unusual for Unix users, where an explicit source is needed, but was the only possibility in MS-DOS). This means directory changes and environment variables affect the original interactive shell too.

Put setlocal at the top of your script to make it run in its own context – you can safely use cd inside the script then.