How to change current working directory using a batch file

Batch FileDirectoryCommand PromptDrive

Batch File Problem Overview

I need some help in writing a batch file. I have a path stored in a variable root as follows:

set root=D:\Work\Root

Then I am changing my working directory to this root as follows:

cd %root%

When I execute this batch file from anywhere on the D drive this is done successfully. But when I execute the same batch file from some other drive, cd %root% doesn't work.

Is there a way I can get the drive letter from the root variable? I can then change the current directory to this drive first and then cd %root% shall work.

Batch File Solutions

Solution 1 - Batch File

Specify /D to change the drive also.

CD /D %root%

Solution 2 - Batch File

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

Solution 3 - Batch File

Try this

chdir /d D:\Work\Root

Enjoy rooting ;)

Solution 4 - Batch File

A simpler syntax might be

pushd %root%

Solution 5 - Batch File

In my batch file I needed to :

  1. Change dir to other directory
  2. run commands in bat file -- do some work in that directory
  3. change back to my original directory

pushd solved this with the help of popd

bat file example

pushd <my-working-directory>
do command
do other command


popd moved me back to original directory.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnanyaView Question on Stackoverflow
Solution 1 - Batch FileAndriy MView Answer on Stackoverflow
Solution 2 - Batch FileGabeView Answer on Stackoverflow
Solution 3 - Batch Filestingray_View Answer on Stackoverflow
Solution 4 - Batch FileNapkinBobView Answer on Stackoverflow
Solution 5 - Batch FileraddevusView Answer on Stackoverflow