Pass variable to filename in Windows FOR / DO Batch File
I have the following code where I systematically go through and compress each file individually. I don't care what the file name is, but I want it hidden more or less so will just call each file "file 1", "file 2", "file 3" etc.
But how do I pass the variable fn=file!count!
to the 7z.exe command line? I added the echo
commands just to make sure the variable was working, and it does. But how do I get fn to resolve as actual "file1" "file2", etc in the 7z command line? I've tried %, !, %!, !%, %%... lol. It just gives a blank file name or !fn! or %fn% not the actual variable value.
Code is here and thanks in advance for any assistance:
setlocal enableextensions enabledelayedexpansion
cd /d E:\Temp\ziptest\Documents
set /A count=0
for /r %%a in (*) do (
cd "%%~pa"
set /A count += 1
echo !count!
set fn=file!count!
echo !fn!
pause
REM 7z.exe a -mx9 -mmt12 -sdel -pt3st! -mhe=on "!fn!.7z" "%%~nxa"
)
endlocal
Example of output where you can see it's incrementing properly and resolving file## properly as well:
E:\Temp\ziptest>setlocal enableextensions enabledelayedexpansion
E:\Temp\ziptest>cd /d E:\Temp\ziptest\Documents
E:\Temp\ziptest\Documents>set /A count=0
E:\Temp\ziptest\Documents>for /R %a in (*) do (
cd "%~pa"
set /A count += 1
echo !count!
set fn=file!count!
echo !fn!
pause
REM 7z.exe a -mx9 -mmt12 -sdel -pt3st! -mhe=on "!fn!.7z" "%~nxa"
)
E:\Temp\ziptest\Documents>(
cd "\Temp\ziptest\Documents\"
set /A count += 1
echo !count!
set fn=file!count!
echo !fn!
pause
REM 7z.exe a -mx9 -mmt12 -sdel -pt3st! -mhe=on "!fn!.7z" "Book1.xlsx"
)
1
file1
Press any key to continue . . .
E:\Temp\ziptest\Documents>(
cd "\Temp\ziptest\Documents\"
set /A count += 1
echo !count!
set fn=file!count!
echo !fn!
pause
REM 7z.exe a -mx9 -mmt12 -sdel -pt3st! -mhe=on "!fn!.7z" "COVID-19 Oakland County.xlsx"
)
2
file2
Press any key to continue . . .
I have fillings that all you need to do is call something
Obs.: Remove extra space in set /A count[espace]+=1
and use @echo off
and replace %%~pa
to %%~dpa
@echo off
cd/d "E:\Temp\ziptest\Documents"
setlocal enabledelayedexpansion
for /r %%a in (*) do (
set /A "count+=1+0"
cd /d "%%~dpa"
set "fn=file!count!"
echo\!fn!
echo\!count!
7z.exe a -mx9 -mmt12 -sdel -pt3st -mhe=on "!fn!.7z" "%%~nxa"
)
endlocal
- Sort compacted option...
@echo off
cd /d "E:\Temp\ziptest\Documents" && setlocal enabledelayedexpansion
for /r %%a in (*)do set /A "count+=1+0" && cd /d "%%~dpa" && call set "fn=file!count!" && (
echo\!fn! & echo\!count! && call 7z.exe a -mx9 -mmt12 -sdel -pt3st! -mhe=on "!fn!.7z" "%%~nxa"
)
endlocal