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

Jerold Schulman

December 23, 2001

1 Min Read
ITPro Today logo in a gray background | ITPro Today


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%popdfor /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>testscriptD:ZZZBackup>for /F "Tokens=*" %i in ('CD') do set CurDir=%iD:ZZZBackup>set CurDir=D:ZZZBackupD:ZZZBackupD:ZZZBackup>pushd "C:Documents and SettingsJerrymy documents"C:Documents and SettingsJerryMy Documents>for /F "Tokens=*" %i in ('CD') do set CurDir=%iC:Documents and SettingsJerryMy Documents>set CurDir=C:Documents and SettingsJerryMy DocumentsC:Documents and SettingsJerryMy DocumentsC:Documents and SettingsJerryMy Documents>popdD:ZZZBackup>for /F "Tokens=*" %i in ('CD') do set CurDir=%iD:ZZZBackup>set CurDir=D:ZZZBackupD:ZZZBackupD:ZZZBackup>



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like