Link to home
Start Free TrialLog in
Avatar of GarySB
GarySB

asked on

Batch Command - Add File Names

Any ideas how to write all file names in a folder to a single new text file using batch commands? Thank You
ASKER CERTIFIED SOLUTION
Avatar of dqmq
dqmq
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jimmart
jimmart

I don't really have enough info from you question to give you a perfect answer but this batch file will probably do what you need:

@echo off
:: ListAllFiles.cmd
:: Will list all files in a directory and display them or put the list of name into a file.

setlocal enableextensions

if not "%~1"=="/?" goto:nohelp

:help
echo Will place a list of all files in a directory into a file or to the screen.
echo.
echo %~n0 [/h] directory [filename]
echo.
echo        /h  List hidden files also.
echo directory  The directory to list the files from.
echo            Use a dot (.) for the current directory.
echo  filename  The filename to store the list.
echo            If no filename is given the list will be displayed on the screen.
goto:EOF

:nohelp
set _scriptname=%~n0

:: Test for /h flag.
set _dirflag=/a-d-h
if "%~1"=="/h" set _dirflag=/a-d
if "%~1"=="/H" set _dirflag=/a-d
if "%_dirflag%"=="/a-d" shift

set _directory=%~1
:: Test that the directory exists.
if exist "%_directory%\*.*" goto:directory_exists
echo The %_directory% directory does not exist.
:abort
echo %_scriptname% aborted.
goto:EOF

:directory_exists
set _filename=%~2
if "%_filename%"=="" goto:show_list
:: Test if the filename exists.
if NOT exist "%_filename%" goto:filename_new
:overwrite_ask
SET /P _answer=There is already a "%_filename%" file. Overwrite [y^|n]? 
if "%_answer%"=="y" goto:filename_delete
if "%_answer%"=="Y" goto:filename_delete
if "%_answer%"=="n" goto:abort
if "%_answer%"=="N" goto:abort
goto:overwrite_ask

:filename_delete
del "%_filename%"
if NOT exist "%_filename%" goto:filename_new
echo Unable to delete "%_filename%".
goto:abort

:filename_new
:: Ensure we can create filename.
echo.>"%_filename%"
if exist "%_filename%" goto:filename_OK
echo Unable to create "%_filename%".
goto:abort

:filename_OK
del "%_filename%"
for /f %%a in ('dir %_dirflag% /b /one "%_directory%"') do echo %%a>>"%_filename%"
echo The file %_filename% contains the list of files from "%_directory%".
goto:EOF

:show_list
echo The list of files from "%_directory%" is:
for /f %%a in ('dir %_dirflag% /b /one "%_directory%"') do echo %%a

Open in new window

Avatar of Steve Knight
WOW jimmart... never seen such a long routine to doa one line dir command!!

Steve
Its all in the error checking baby!
Surprised you don't have an option or three to sort it, open it in Notepad when finished etc...

Looks impressive when you justify the 6 week project for producing a directory listing!!

Steve
Avatar of GarySB

ASKER

Perfect Solution!