Home > Windows > Changing Directory in Windows Batch File

Changing Directory in Windows Batch File


Just noticed a small thing yesterday.


set curr_dir=%cd%

chdir /D J:\

REM...do your stuff...

chdir /D %curr_dir%

notice two important things here:

  • The script changes the current working directory to whatever it requires but then switches it back again so that if the user runs the script from a command window he is does not find himself in a strange directory after the script is finished
  • There is a /D switch that needs to be added to chdir so that it changes the drive if required. Without this chdir won’t work ( it had me baffled for quite some time :) )
  1. nick
    October 1, 2010 at 5:14 am

    Thanks ;)

    found this off a google search. I have some batch files I inherited. Making the scripts more dynamic by using the subst command. So now the full path has a drive letter in it, whereas it used to just change to a sub directory. Probem is, it wasnt’ actually changing directories when I do an echo %cd% for the current directory.

    Adding the /d to a cd (chdir) command did the trick!

  2. Puff
    January 12, 2012 at 1:44 am

    Thank you so much this really helped me out!!

  3. Nik
    September 28, 2012 at 6:00 pm

    Thanks a ton, was making a batch file lanuncher but wasnt able to change drives, thanks.

  4. February 20, 2013 at 5:58 pm

    Thank you for posting this steps. It solved my problem !!!

  5. January 3, 2014 at 4:03 pm

    Работаю с этим сайтом http://obnalmc.blogspot.com/.
    Рекомендую. Все честно.

  6. Jaswerl
    July 2, 2014 at 2:10 am

    On a Windows 2008 server the root directory is C:Users/username/desktop. I cannot get a batch file to change the directory to the data drive (e:) regardless if i use \D, CD.., Pushd, setlocal or any other command. File:
    cmd
    SETLOCAL
    CD ..
    CD /D “e:\Sync Tool\programfolder\programsubfolder

    Is there somthing about the “Users” Folder in Windows that I don’t understand??

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: