Skip navigation

JSI Tip 4603. How do I know the current directory, change directories, and return, in a batch job?


To know the current directory:

for /f "Tokens=*" %%i in ('CD') do set CurDir=%%i

To change directories, you can use the CD command to change to a folder on the same drive. To change to a folder on a different drive, you can use CD /D. I prefer to use the Pushd command, which works in both situations.

To change to your My Documents folder:

pushd "%userprofile%\my documents"

To return to the previous directory, if you used the Pushd command:

popd

Here is a little script to prove the point:

for /f "Tokens=*" %%i in ('CD') do set CurDir=%%i
@echo %CurDir%
pushd "%userprofile%\my documents"
for /f "Tokens=*" %%i in ('CD') do set CurDir=%%i
@echo %CurDir%
popd
for /f "Tokens=*" %%i in ('CD') do set CurDir=%%i
@echo %CurDir%
When I run it from my D:\ZZZBackup folder, the console displays the following:
D:\ZZZBackup>testscript
D:\ZZZBackup>for /F "Tokens=*" %i in ('CD') do set CurDir=%i
D:\ZZZBackup>set CurDir=D:\ZZZBackup
D:\ZZZBackup
D:\ZZZBackup>pushd "C:\Documents and Settings\Jerry\my documents"
C:\Documents and Settings\Jerry\My Documents>for /F "Tokens=*" %i in ('CD') do set CurDir=%i
C:\Documents and Settings\Jerry\My Documents>set CurDir=C:\Documents and Settings\Jerry\My Documents
C:\Documents and Settings\Jerry\My Documents
C:\Documents and Settings\Jerry\My Documents>popd
D:\ZZZBackup>for /F "Tokens=*" %i in ('CD') do set CurDir=%i
D:\ZZZBackup>set CurDir=D:\ZZZBackup
D:\ZZZBackup
D:\ZZZBackup>


Hide comments

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.
Publish