-1

I want to process all files in a directory, eg. replace the extension and rename the file. The problem is, I cannot move the filename into a variable (seems to be a problem with the scope of variables).

Here is what I have coded:

@echo off
cls

setlocal
set myname=hugo
echo myname=%myname%

::process all files in directory
for %%f in (C:\windows\*.ico) do (
   echo F=%%f                <--- this works fine
   set myname=%%f            <--- this does NOT work!
   echo.myname=%myname%
)
echo myname=%myname%         <--- displays last set
endlocal

And this is the output:

myname=hugo
F=C:\windows\AnyWeb Print.ico
myname=hugo
F=C:\windows\Dr. Printer Icon.ico
myname=hugo
F=C:\windows\SmartCMS2.ico
myname=hugo
myname=C:\windows\SmartCMS2.ico

I cannot modify the variable "myname" within he loop, but once the loop has ended, it contains the value, that I have tried to assign most recently.

Obviously I don't understand the way a batch file handles variables in a FOR loop. I seem to lack some info about it.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Peter329
  • 11
  • 4
  • Does this answer your question? [Example of delayed expansion in batch file](https://stackoverflow.com/questions/10558316/example-of-delayed-expansion-in-batch-file) or [Variables are not behaving as expected](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected). I can assure you the `set` command does work, but it is the expansion of `%myname%` that is failing… – aschipfl Jan 14 '22 at 17:52
  • This is my coding now: ::process all files in directory setlocal enabledelayedexpansion for %%f in (C:\windows\*.ico) do ( echo F=%%f set myname=%%f echo.N=!myname! call :strlen myLen "!myname!" echo.myLen=!myLen! set /A L=myLen-3 + 1 set str=!myname! echo.str1=!str! L=!L! set str=!str:~0,!L! ! echo.str2=!str! ) Here is the output of my call : F=C:\windows\AnyWeb Print.ico N=C:\windows\AnyWeb Print.ico Strlen C:\windows\AnyWeb Print.ico myLen=25 str1=C:\windows\AnyWeb Print.ico L=23 str2=L <--- what went wrong ???? – Peter329 Jan 15 '22 at 13:15

1 Answers1

0

The expansion of variables inside FOR loops requires you to enable delayed expansion to force variables to be expanded at runtime instead of being expanded when parsed. Read HELP SET for more information.

And try changing your code to

setlocal enabledelayedexpansion
for %%f in (C:\windows\*.ico) do (
   set myname=%%f
   echo !myname!;
)

Note that the variable is referenced with an slightly different syntax !myname! instead of %myname%. Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time.

PA.
  • 28,486
  • 9
  • 71
  • 95