Win Batch: Help defining variable in a FOR loop - windows

I made this script that finds all directories and echoes the directorie's name to a .txt file. The script is working but it ends up echoing only %A without any value. My script is below!
set /a count=0
setlocal EnableDelayedExtensions
FOR /D %%A in ("*") DO (call :sub)
endlocal
pause
exit
:sub
(echo [DIR] %%A)>>%count%.txt
set /a count+=1
The output in the .txt files is [DIR] %A.
Any idea how to fixe this? Thanks -David

First remark, you are using an invalid option for setlocal but that is probably just a typo.
The problem is that you are try to use a for-parameter where it cannot be used.
The rule is "A for-parameter can only be used within the command or command block () of a for loop"
Your subroutine is not within the command block of a for loop, but you can start a dummy for loop in the subroutine which will give you access to all available for-parameters.
set /a count=0
setlocal EnableDelayedExpansion
FOR /D %%A in ("*") DO (call :sub)
endlocal
pause
exit/b
:sub
For %%. in (.) do (echo [DIR] %%A)>>%count%.txt
set /a count+=1

You need to pass the parameter to the subroutine.
From https://www.informit.com/articles/article.aspx?p=1154761&seqNum=11 :
for %%f in (*.dat) do call :onefile %%f
exit /b
:onefile
echo Processing file %1...
echo ... commands go here ...
exit /b

As you've already enabled delayed expansion, there's no need to use a Call to a label, just do it within the loop.
#Echo Off
SetLocal EnableExtensions EnableDelayedExpansion
Set "count=0"
For /D %%G In (*) Do (
Set /A count += 1
(Echo [DIR] %%G) 1>"!count!.txt"
)
On this version, I've started at 1 instead of 0 for the first text file name, if you really want to start at 0, change line 3 to Set "count=-1"

Related

Batch script does not echo contents of a variable and pause not working

I am working on a script which iterates over every file in a specific folder and reads some information from, and numbers each.
So I am running over the files with a for-loop and that is working correctly. Now I added a variable i which should increment on each iteration of the loop.
I used set /a i=0 and inside the for-loop set /a i+=1 and this Set command does print the number to console. My problem now is that the set command prints the number, but when I echo the number with echo %i% it will always print 0 and not the increasing value. I also tried echo !i! but that does not work at all. It just prints !i! in the console.
I also added a pause command to the end of the script, but that gets ignored entirely.
This is my batch script:
#echo off
setlocal EnableDelayedExpansion
set /a i=0
for /r %%n in (Links\*.lnk) do (
set /a i+=1
echo.
echo [Button!i!Back]
get.bat "%%n"
)
pause
This is an example of the output:
45
[Button!i!Back]
###HudIcons\VLC media player.ico
D:\Programme\VideoLAN\VLC\vlc.exe
I also just realized, that for the first time the loop runs, the !i! does work correctly and prints the number, but not afterwards.
I know that I should probably not be calling the other batch file like this, but that is temporary.
Any ideas why this is behaving so weird?
Perhaps it would be easier for you without the Set /A incrementing method, and therefore no need for delayed expansion. The alternative methodology could involve using findstr.exe to provide the counting:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
For /F "Tokens=1,* Delims=:" %%G In ('Dir /B /S /A:-D "Links\*.lnk" ^
2^> NUL ^| %SystemRoot%\System32\findstr.exe /EILN ".lnk"') Do (Echo=
Echo [Button%%GBack]
Call "get.bat" "%%H")
Pause
You use percentages symbol to call a variable %Variable%
and to echo it echo %variable%
to set one set variable=value Hope this helps you.

Keep variable after endlocal in Batch

I have a folder structure, which is like for example C:\Temp\ and there are a lot of folder and file, and within each folder there are a "callme.bat". I would like to create a so called main.bat which is one after another call the callme files within the main' window. But there is a problem, within the callme files are some echo which contains "!" mark what make a problem for me.
I realized the problem with the setlocal-endlocal combo, because the batch scrip wants to interpret the message within the "!" marks, so I must use endlocal, but if I did I not able to run the callme bats.
callme.bat
#echo off
echo !!! hidden message !!! not hidden message
pause
main.bat variant 1
#echo off
setlocal enabledelayedexpansion
set PATH=C:\Temp
for /F %%x in ('dir /B/A:D %PATH%') do (
set CURR_DIR=%PATH%\%%x
set ACTUAL_BATCH=!CURR_DIR!\callme.bat
echo !ACTUAL_BATCH!
call !ACTUAL_BATCH!
pause
)
pause
exit
main.bat variant 2
#echo off
set PATH=C:\Temp
for /F %%x in ('dir /B/A:D %PATH%') do (
setlocal enabledelayedexpansion
set CURR_DIR=%PATH%\%%x
set ACTUAL_BATCH=!CURR_DIR!\callme.bat
echo !ACTUAL_BATCH!
ENDLOCAL & SET VAR=!ACTUAL_BATCH!
echo %VAR%
pause
)
pause
exit
main.bat variant 3
#echo off
set PATH=C:\Temp
for /F %%x in ('dir /B/A:D %PATH%') do (
setlocal enabledelayedexpansion
set CURR_DIR=%PATH%\%%x
set ACTUAL_BATCH=!CURR_DIR!\callme.bat
echo !ACTUAL_BATCH!
REM source: https://stackoverflow.com/questions/3262287/make-an-environment-variable-survive-endlocal
for /f "delims=" %%A in (""!ACTUAL_BATCH!"") do endlocal & set "VAR=%%~A"
echo %VAR%
call %VAR%
pause
)
pause
exit
So I don't know what to do. Anyone has an idea?
variant 1's output:
C:\Temp\1\callme.bat
not hidden message
C:\Temp\2\callme.bat
not hidden message
variant 2-3's output:
C:\Temp\1\callme.bat
ECHO is off.
C:\Temp\2\callme.bat
ECHO is off.
TL;DR
ENDLOCAL&set "varname=%sourcevarname%"
probably, where varname is the variablename to set and sourcevarname is the variable whose value is to be assigned to varname - and they CAN be the same name, even if the statement appears logically null - it's exporting the variable from within the setlocal/endlocal block.
Key point: MUST be on one physical line and may be repeated if necessary (ie
ENDLOCAL&set "varname=%sourcevarname%"&set "varname2=%sourcevarname2%"
So
ENDLOCAL&set "fred=%fred%"&set "bill=%george%"
is perfectly valid, to set the value of fred outside the setlocal/endlocal bracket to its final value inside and of billoutside to the final value of george inside.
Some points about your code:
Never use PATH as a variable name, as it destroys the PATH variable for searching executable files.
Use the extended SET syntax set "varname=content" to avoid problems with trainling spaces.
You only need to disable the delayed expansion mode by using setlocal DisableDelayedExpansion
#echo off
setlocal EnableDelayedExpansion
set MY_PATH=C:\Temp
for /F %%x in ('dir /B/A:D %PATH%') do (
set "CURR_DIR=%MY_PATH%\%%x"
set "ACTUAL_BATCH=!CURR_DIR!\callme.bat"
call :execute ACTUAL_BATCH
pause
)
pause
exit /b
:execute ACTUAL_BATCH
set "batFile=!%~1!"
echo Calling !batFile!
setlocal DisableDelayedExpansion
call %batFile%
endlocal
exit /b

Windows batch script "The system cannot find the file specified." with exclamation in filenames?

I am trying to write a batch script that does the following:
When a folder is drag-and-dropped onto the batch script, it processes every file in that folder.
I am running into a problem with a certain filenames that contain exclamation marks. e.g.:
!.txt or !!!.txt
For now, I am simply trying to rename the file to demonstrate the issue:
#echo off
SetLocal EnableDelayedExpansion
set folder=%~1
set count=0
for /r "%folder%" %%G in (*) do (
set fullpath=%%G
set fileExtension=%%~xG
call :processFile
)
goto end
:processFile
echo "fullpath = %fullpath%"
echo "fileExtension = %fileExtension%"
rename "%fullpath%" "temporary_filename_500%fileExtension%"
set /a count+=1
echo.
goto :eof
:end
echo "%count% files processed."
pause
It gives me the error "The system cannot find the file specified." However, it works if I change the filename to something simple like "test.webm" How can I make the script more robust?
I don't see that you are using somewhere delayed expansion. So, either disable it with setlocal DisableDelayedExpansion in the start of your batch file or just remove it by removing line setlocal EnableDelayedExpansion.
However, if you want to keep it, do:
#echo off
SetLocal EnableDelayedExpansion
rem Code above (^^) if exists.
Setlocal DisableDelayedExpansion
set "folder=%~1"
set "count=0"
for /R "%folder%" %%G in (*) do (
set "fullpath=%%~fG"
set "fileExtension=%%~xG"
call :processFile
)
goto end
:processFile
echo "fullpath = %fullpath%"
echo "fileExtension = %fileExtension%"
ren "%fullpath%" "temporary_filename_500%fileExtension%"
set /a "count+=1"
echo/
goto :eof
:end
echo "%count% files processed."
pause
setlocal EnableDelayedExpansion
rem Your code below with active delayed expansion:
Note that:
You should always quote the variable name and the value in the set command like set "var=value" and in set /a like set /a "var+=1", etc.; see set /? for more information.
To find the full path of a file/folder for sure in a for loop, use the f modifier, like %%~fG.
Mentioned by Mofi here: don't use echo.; use echo/ for better practice.
See also the Phase 5 (Delayed Expansion) of this answer about how batch files are interpreted.

How can I check if I am at EOF when reading a file from a CMD Batch.bat?

I'm trying to fill X files with chunks of content from a .txt file.
The thing is the .txt (source) file is small and I want my code to loop over it's content chunk by chunk and start again when no more chunks are avaliable until all files have been filled.
This is part of the (still on development) code. I've managed to teach my Batch.bat to recognized the chunks but I don't know how to check if I am at EOF to go back again to the begining.
Current code doesn't work since it has been simplified for the question (delayed expansion not present)
SET /A J=1
FOR /F "skip=%J% tokens=*" %%A IN (%~1%) DO (
CALL :CSV "%%A" %J%
)
EXIT /B
:CSV
SETLOCAL
IF NOT "%~1"=="---" (
ECHO %~1 >> Chistaco.txt
)
ENDLOCAL && SET /A J=%2+1
Code posted here is just a guide of my target, don't miss the question.
Thank you !
EDIT: Simplified Code Module
#ECHO OFF
SETLOCAL
REM Ask for parameters
SET /P filler=Enter the name of the file to use as filler (file.ext):
SET /P seed=Enter the seed of the files to fill:
CLS && ECHO %~1%
REM The variable "J" counts the lines to jump in "file.ext" (and btw, it cannot be 0 as the batch parses fails to read it)
REM This is where the EOF check is needed: "J" must be referenced outside the main loop so the script can loop inside "file.ext" untill all "seed???" files have been filled
SET /A J=1
FOR /R "%path%" %%X IN (%seed%*) DO ECHO %%X && CALL :FillerChomper "%filler%" "%%X"
ENDLOCAL
EXIT /B
:FillerChomper
SETLOCAL
FOR /F "skip=%J% tokens=*" %%A IN (%~1%) DO (
CALL :CSV "%%A" J %2%
IF "%%A"=="---" EXIT /B
)
EXIT /B
:CSV
SETLOCAL
IF NOT %1=="---" ECHO %~1 >> %~3%
ENDLOCAL && SET /A %2=%J%+1
EXIT /B
REM All functions must have a "EXIT /B" command or batch will just keep executing codelines until :EOF
Thank you guys for your help!

Windows batch: Reset Variable

I am trying to collect first file from the directory then process the file. But at the second time when the running and processing the batch file I am unable to store the values in the variable for the file name
Below is the sample code:
for /R C:\abcde_efghij\ab_abcabca %%i IN (*.*) DO (
set filename=%%i
set newname=%filename:~14%
set transname=%filename:~25%
goto tests
)
:tests
echo %filename%
echo %newname%
echo %transname%
I am sure we have to use something called SETLOCAL but I am unable to make it in the above code.
Any Help!
You should avoid percent expansion inside of blocks, also FOR blocks, as the expansion only occours only once when the block is parsed.
for /R C:\abcde_efghij\ab_abcabca %%i IN (*.*) DO (
set filename=%%i
goto :tests # Get only the first file
)
exit /b
:tests
set newname=%filename:~14%
set transname=%filename:~25%
echo %filename%
echo %newname%
echo %transname%
exit /b
As #Stephan noted, you could also use delayed expansion inside blocks.
setlocal EnableDelayedExpansion
for /R C:\abcde_efghij\ab_abcabca %%i IN (*.*) DO (
set filename=%%i
set newname=!filename:~14!
set transname=!filename:~25!
goto :tests # Get only the first file
)

Resources