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

92

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

If you want to upgrade from batch to powershell:

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

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

Solution 3

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!
)
Share:
92

Related videos on Youtube

Cobra
Author by

Cobra

Updated on September 17, 2022

Comments

  • Cobra
    Cobra over 1 year

    I want to find a file from current directory the executable is running, say -

    delta001.png
    

    if it does not exists then print it.

    If it exists then print -

    delta002.png
    

    The name of the file to be printed is 'delta' but the number would be the next number which is found in the directory. The number could be anything like - '112', 334, 234, 087 etc. Python 3 or higher.

    Thanks in advance.

  • Joey
    Joey over 13 years
    Or simply gci <path> | select Name.
  • Ryflex
    Ryflex over 10 years
    He also needs to use something like os.path.exists("delta.png") to check if the file exists or not
  • kylieCatt
    kylieCatt over 10 years
    Will glob find things that aren't there?
  • Ryflex
    Ryflex over 10 years
    Thanks @p99will, didn't spot that when I wrote it.
  • p99will
    p99will over 10 years
    :D, Thanks. Only problem is knowing if this works for Python 3 Python 3 or higher. As it think OP wants. I don't know anything about Py3.
  • Cobra
    Cobra over 10 years
    Seems like it works, but in my case looping 999 times is not a good idea. It makes the application unresponsive. Thanks.
  • Cobra
    Cobra over 10 years
    Ok, this seems to be working fine. I can't up vote, sorry, my rep is low and just lost one :). Thanks.
  • Sandra K
    Sandra K over 6 years
    This works even if file name has spaces in it?
  • Dennis Williamson
    Dennis Williamson over 6 years
    @SandraK: For many uses you should quote the %%f at the end. I've added some additional information to my answer.