How to query current Directory name into a variable for batch files

I have been researching and trying without success to get the current directory name into a variable such as %CurrDirNam% for creating a text file with the same folder name something the third example below which works, however when run, it overwrites the existing file and it's contents, so I modified the bottom line to check for the file's existence. Set DirName=%cd% For %%A in ("%dirname%") do ( Set Name=%%~nxA ) IF NOT EXIST %Name%.txt Echo %Dirname% > %DirName%\%Name%.txt Rem ---OOPS sorry I do not know how to re-format the code with CRLF and indents. I'm new at this...

6

2 Answers

If you run this

Set DirName=%cd%
Echo %Dirname% > %DirName%.txt

from C:\Temp, it will expand to

Set DirName=C:\Temp
Echo C:\Temp > C:\Temp.txt

This will fail if you don't have write permissions on C:\ and would explain the Access Denied message you get.

If you want to create a file in C:\Temp, use something like this:

Set DirName=%cd%
Echo %Dirname% > %DirName%\test.txt

If the name of the file must match the directory name, use this trick:

Set DirName=%cd%
For %%A in ("%dirname%") do ( Set Name=%%~nxA
)
Echo %Dirname% > %DirName%\%Name%.txt
4

I tested this on my Windows 10 system and it worked with no problem.

>path.txt echo %cd%

I ran this in a batch script while in the directory I wanted the path of. In my case, I only wanted the path to create a URL from it I found that by using >url.txt echo %cd:\=/% it also takes care of all the backslashes that needed to be forward slashes in the URL and saved me the trouble

Only step left is a little editing on the url.txt file

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like