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

Time:06-04

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!

CodePudding user response:

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"
  • Related