Feketenyek
Feketenyek

Reputation: 29

Batch file to write names of files in a folder and the path of the parent directory to a text file

I am trying to as the title suggests, use a batch file to copy the name of all files and the path of the parent directory where the batch file is to a text file. I have search previous posts but have not come across any posts that solve my issue.

So far I am able to write all file names (no patch or folder names) using the following batch command titled dir.bat located C:\Users\Username\Documents\FolderName:

dir /b /a-d > fileslist.txt

This outputs a text file in the same folder where the batch file is found:

dir.bat
fileslist.txt
New Text Document - Copy (2).txt
New Text Document - Copy (3).txt
New Text Document - Copy (4).txt
New Text Document - Copy (5).txt
New Text Document - Copy.txt
New Text Document.txt

Is there any way to add a line in the batch file so that the text file has the path of the parent directory either at the start or end like this:

C:\Users\Username\Documents\FolderName

dir.bat
fileslist.txt
New Text Document - Copy (2).txt
New Text Document - Copy (3).txt
New Text Document - Copy (4).txt
New Text Document - Copy (5).txt
New Text Document - Copy.txt
New Text Document.txt

This is my first post so if there is any more information that I can give to help guide responses please let me know! Thank you in advance!

Upvotes: 0

Views: 1776

Answers (2)

yonni
yonni

Reputation: 352

If you add the cd /d %~dp0 command to the beginning of the batch file, the current work directory will always be changed to the folder where the batch file is located...

Then, you can add the following lines:

(
echo %~dp0
dir /b /a-d
) >> filelist.txt

Upvotes: 0

Compo
Compo

Reputation: 38719

Your dir command is not listing all of the files in the same directory as the batch file. It is listing all the files in the current working directory. You are simply lucky that the method you are using to execute the batch file is using the batch file directory as the current directory.

In order to correctly output what you require, I'd suggest a simple one liner:

@(For %%G In ("%~dp0.") Do @Echo %%~fG& Echo(& Dir "%~dp0" /B /A:-D) 1>"filelist.txt"

Upvotes: 1

Related Questions