JSI Tip 8782. How can I determine the current drive and path in a batch, and/or walk up the tree?

The command processor, CMD.EXE automatically defines the CD environment variable. Open a CMD.EXE window and type CD /D "%UserProfile%\My Documents" and press Enter. Then type @echo %CD% and press Enter to display the current directory.

If you wanted to go to the parent folder, type CD .. and press Enter.

If you wanted to script a process that displays the current directory, and each higher parent folder, until the root of the current drive is displayed, you could use the following script:

@echo off
@echo %cd%
if "%CD:~3,1%" EQU "" goto finish
cd ..
goto loop
If I open a CMD.EXE window and set the current directory using CD /D "%UserProfile%\My Documents", and then run a batch file that contains the above script, the following is displayed:
C:\Documents and Settings\Jerry\My Documents
C:\Documents and Settings\Jerry
C:\Documents and Settings
NOTE: See How can I extract the last sub-folder from a fully qualified fold path?.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.