I need a script that inserts a number at some point into a file path, like this: from C:\WINDOWS\system32\ansi.sys to C:\WINDOWS\system32\5.ansi.sys
I made a function using a label and it seems to work fine, until I invoke it from within a FOR loop.
This is the code I wrote:
@ECHO OFF
SET PATHTOPROCESS="C:\WINDOWS\system32\ansi.sys"
call :GetNewFilePath NEWPATH %PATHTOPROCESS% 7
echo New file name: %NEWPATH%
call :GetNewFilePath NEWPATH %PATHTOPROCESS% 5
echo New file name: %NEWPATH%
FOR /L %%i in (1,1,2) DO (
call :GetNewFilePath NEWPATH %开发者_如何转开发PATHTOPROCESS% %%i
echo New file name in FOR loop: %NEWPATH%
)
goto :eof
:GetNewFilePath
SETLOCAL
SET PINDEX=%~3
SET PDIRECTORY=%~dp2
SET PFILE=%~nx2
SET LocalVar1=%PDIRECTORY%%PINDEX%.%PFILE%
ENDLOCAL & IF "%~1" NEQ "" SET %~1=%LocalVar1%
goto :eof
and this is the output I get:
New file name: C:\WINDOWS\system32\7.ansi.sys
New file name: C:\WINDOWS\system32\5.ansi.sys
New file name in FOR loop: C:\WINDOWS\system32\5.ansi.sys
New file name in FOR loop: C:\WINDOWS\system32\5.ansi.sys
and this is what I expect:
New file name: C:\WINDOWS\system32\7.ansi.sys
New file name: C:\WINDOWS\system32\5.ansi.sys
New file name in FOR loop: C:\WINDOWS\system32\1.ansi.sys
New file name in FOR loop: C:\WINDOWS\system32\2.ansi.sys
It seems that in the FOR loop, the variable is reverted back to the value it had before calling the function. Is there some special trick required for this when using FOR?
Thank you.
The variables inside the for
loop are expanded immediately when that block is parsed, not when it's run. You'll need to use delayed expansion:
rem this should preferrably go at the very start of the batch file
setlocal enabladelayedexpansion
...
FOR /L %%i in (1,1,2) DO (
call :GetNewFilePath NEWPATH %PATHTOPROCESS% %%i
echo New file name in FOR loop: !NEWPATH!
)
Otherwise %NEWPATH%
would be expanded to the value it had before the loop and inside the loop there wouldn't be any variable left.
You can easily verify that when removing the echo off
at the start, by the way. The loop's block would then show the expanded value before it even ran. See help set
for a more in-depth discussion of delayed expansion.
精彩评论