3

I have a folder folder1 contain 3 files file1, file2 and file3, etc.

I need command line to do the following task.

Store the name of the files in a variable because I want to write a dynamic batch.

3 Answers 3

4
FOR %%f in (folder1\*) DO @echo %%f

in a batch file will echo the filename of each file in the folder. To do the same thing at the command line, use only one percent sign for the variable. You can replace echo with some other command.

If you quote the %%f, the echo will output the quotes around the filename, but if you want to pass the filename to other commands the quotes may be necessary if there are special characters, such as spaces, in the filenames. For example, to output the contents of all the files:

FOR %%f in (folder1\*) DO @type "%%f"

Without the quotes, if there was a file named "Has Space", type would try to output the contents of two files, "Has" and "Space". With the quotes, it will work as intended.

2
  • This works even if file name has spaces in it?
    – Sandra K
    Dec 20, 2017 at 19:49
  • @SandraK: For many uses you should quote the %%f at the end. I've added some additional information to my answer. Jan 6, 2018 at 16:11
1

Assuming this is in a batch file, you could do it in a for loop like this:

setlocal EnableDelayedExpansion 

for %%a in (folder1\*) do (
set fileVariable=%%a
echo !fileVariable!
)
1

If you want to upgrade from batch to powershell:

Foreach ($file in Get-Childitem "<PATH>") {
    $file.name
}

$filenames = (Get-ChildItem -Path "PATH" -Directory).Name
1
  • Or simply gci <path> | select Name.
    – Joey
    Dec 23, 2010 at 22:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .