Get folder and file names and store it in a variable in windows?

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.


Solution 1:

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.

Solution 2:

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!
)

Solution 3:

If you want to upgrade from batch to powershell:

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

$filenames = (Get-ChildItem -Path "PATH" -Directory).Name