1

I want that my batch script only shows the filename without any path or extension in a specific directory of *.exe files. My code so far is this:

for /R "%cd%" %%e in (*.exe) do (
    set "EXENAME=%%~ne"
    echo "%EXENAME%"
)

But this code does not work as expected. Let's assume, I have two files in that directory: tomcat7.exe and tomcat7w.exe. But when processing the script, I get as an answer this:

"tomcat7w"
"tomcat7w"

Why is that?

Mofi
  • 46,139
  • 17
  • 80
  • 143
devopsfun
  • 1,368
  • 2
  • 15
  • 37
  • why aren't you using the `dir` command ? – naurel Apr 29 '16 at 09:03
  • 2
    See `set /?`, `for /?`, and `setlocal /?` (enabledelayedexpansion). –  Apr 29 '16 at 09:17
  • 1
    Possible duplicate of [Batch file variables initialized in a for loop](http://stackoverflow.com/questions/691047/batch-file-variables-initialized-in-a-for-loop) – aschipfl Apr 29 '16 at 15:10

2 Answers2

1

You ran into the delayed expansion trap as so many batch file coding newbies as Noodles hinted.

You could see the expected result by using echo %%~ne instead of echo "%EXENAME%".

By opening a command prompt window, running in this window set /? and reading the output help you get delayed environment variable expansion explained on an IF and a FOR example.

The batch file producing the expected output:

@echo off
setlocal EnableDelayedExpansion
for /R "%cd%" %%e in (*.exe) do (
    set "EXENAME=%%~ne"
    echo !EXENAME!
)
endlocal
Community
  • 1
  • 1
Mofi
  • 46,139
  • 17
  • 80
  • 143
1

If you want to see with extensions try like this way :

@echo off
setlocal EnableDelayedExpansion
for /R "%cd%" %%e in (*.exe) do (
    set "EXENAME=%%~nxe"
    echo !EXENAME!
)
endlocal
pause
Hackoo
  • 18,337
  • 3
  • 40
  • 70