131

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.

bubble
  • 3,408
  • 5
  • 29
  • 51
Ananya
  • 1,503
  • 3
  • 12
  • 8

5 Answers5

189

Specify /D to change the drive also.

CD /D %root%
Andriy M
  • 76,112
  • 17
  • 94
  • 154
  • 1
    Other answers say `\d` (lowercase) is there a difference between either? Is the option just case-insensitive? – josch Feb 28 '17 at 12:41
  • 3
    @josch: Yes, if we are talking about CMD's internal commands, then switch parameters like `/D` above are case-insensitive (`/D` = `/d`), just like the commands themselves (`CD` = `cd`). I believe that is also true for all external Windows command-line utilities (like `FINDSTR`, `SORT` etc.) Third-party tools, on the other hand, can use case-sensitive parameters. – Andriy M Feb 28 '17 at 13:36
  • not worth an own answer, but you can `set "root=/d D:\Work\Root"` and `cd %root%` or even `set "root=cd /d D:\Work\Root"` and just `%root%` – Stephan Feb 25 '20 at 14:47
47

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.

Gabe
  • 84,912
  • 12
  • 139
  • 238
37

Try this

chdir /d D:\Work\Root
Ryan M
  • 18,333
  • 31
  • 67
  • 74
stingray_
  • 564
  • 5
  • 13
  • It should be noted that before and after directory, " should be put like this; chdir /d "D:\Work\Root" – Ad Infinitum Mar 16 '17 at 14:06
  • @AdInfinitum No that's not true, that's only necessary if there's spaces in the path. Just qouting the spaced words works as well, like `C:\"Program Files"\Something\Something` – Zimano Nov 24 '20 at 12:49
22

A simpler syntax might be

pushd %root%

NapkinBob
  • 632
  • 7
  • 19
5

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 

popd moved me back to original directory.

raddevus
  • 8,142
  • 7
  • 66
  • 87