setlocal
for /F "tokens=1,2" %%a in (%env_cells%) do (
call :env_setter env_setter_%%a
)
goto:EOF
:env_setter
rem doesn't do anything
endlocal
call %%1
goto:eof
The problem is the above disables the setting of global variables in all calls spawned by :env_call. Is there a way to resolve this?
Perhaps this is a more detailed explanation:
env_setter is a call to a batch file that itself contains set calls with the intention to set environment variables on this calling context. Because setlocal is enabled during the call to !env_cell! and the endlocal in :env_cell does not appear to disable endlocal, said set calls do not change this context as intended.
In this particular example, one can use %%a but I wish to understand this functionality in general.
Is there a manual way to access a variable value reflectively in a if/for block?
Throw your variables over the wall!
#echo off &setlocal
echo(
echo this obviously doesn't work
set "Counter="
for /l %%a in (1 1 5) do (
SETLOCAL ENABLEDELAYEDEXPANSION
set "Counter=!Counter!1"
set "Variable=!Variable!!Counter!"
echo !Counter!:!Variable!
endlocal
)
echo Counter's value in the calling environment : %Counter%
echo Variable's value in the calling environment: %Variable%
echo(
echo throw your variables over the wall!
set "Counter="
for /l %%a in (1 1 5) do (
SETLOCAL ENABLEDELAYEDEXPANSION
set "Counter=!Counter!1"
set "Variable=!Variable!!Counter!"
echo !Counter!:!Variable!
for /f %%a in ('set Counter^&set Variable') do (if "!"=="" endlocal)&set "%%a"
)
echo Counter's value in the calling environment : %Counter%
echo Variable's value in the calling environment: %Variable%
It's not possible to use an endlocal in a function to leave a setlocal which is set outside the function.
But when a syntax error occours all setlocal instances are still alive and can't be removed with endlocal, so this can set global variables.
setlocal
for /F "tokens=1,2" %%a in (%env_cells%) do (
call :env_setter env_setter_%%a
)
goto:EOF
:env_setter
set myNewGlobal=1
call :haltAndStore
goto:eof
:haltAndStore
()
I used #jeb answer to implement assigning IP addresses to environment variables. Possibly my worst hack ever.
#echo off
setlocal enabledelayedexpansion
set _count=1
for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr /i "ipv4"`) do (
for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do (
for /f "tokens=*" %%c IN ('echo %%b') do (set IP!_count!=%%c & echo IP!_count!=%%c & set /a _count+= 1)
)
)
set _count=
call :haltAndStore 2> nul
:haltAndStore
()
Related
I have the following (simplified etc):
#echo off
set searchStr="AAAA"
set workingPaths[0]="C:\Docs\Me\"
set x=0
::Loop1
if defined workingPaths[%x%] (
set currPath=%%workingPaths[%x%]%%
rem set currPath="C:\Docs\Me\"
call echo Searching in: %currPath%
for %%f in (%currPath%*.doc*) do (
findstr /s /m /I /c:%searchStr% "%%f"
)
set /a x+=1
GOTO :Loop1
)
It works perfectly fine if I were to switch the currPath to a singular assignment (where rem is currently), but won't work if the currPath is assigned out of the array.
The subsequent echo is identical regardless of whether currPath is set from the array or the singular assignment.
Anyone any ideas where I'm going wrong? Thanks in advance
I would perform this task a little differently, in that I'd try to better utilise the built-in options of findstr.exe. I would build a listing of the workingPaths and pass those to a single findstr.exe instance, using its /D option.
Example:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Rem Script defined variables [please do not modify].
For /F "Delims==" %%G In ('"(Set workingPaths[) 2>NUL"') Do Set "%%G="
Set "findStr=%SystemRoot%\System32\findstr.exe"
Set "dirList="
Rem User defined variables [modify as necessary]
Set "searchStr=AAAA"
Set "searchGlob=*.doc"
Set "workingPaths[0]=C:\Docs\Me"
Set "workingPaths[1]=C:\Users\Me\Documents"
Set "workingPaths[2]=C:\Users\Me\Desktop"
Rem Directory list builder [please do not modify]
For /F "Tokens=1,* Delims==" %%G In ('"(Set workingPaths[) 2>NUL"'
) Do If Not Defined dirList (Set "dirList="%%~H"") Else (
SetLocal EnableDelayedExpansion
For /F "UseBackQ Delims=" %%I In ('"!dirList!"') Do (EndLocal
Set "dirList=%%~I;"%%~H""))
If Not Defined dirList Exit /B
Rem Main search command [please do not modify]
%findStr% /D:%dirList% /I /L /M /S "%searchStr%" "%searchGlob%"
Rem Optional commands for GUI usage puposes only [remove as necessary]
Pause
GoTo :EOF
I changed
set currPath=%%workingPaths[%x%]%%
to
set currPath=!workingPaths[%x%]!
and its working... albeit it doesn't seem to like iterating the last array entry ('cos I was stupid and typo'd it!).
Leaving a final working solution of:
#echo off
set searchStr="AAAA"
set workingPaths[0]="C:\Docs\Me\"
setlocal enabledelayedexpansion
set x=0
::Loop1
if defined workingPaths[%x%] (
set currPath=!workingPaths[%x%]!
rem set currPath="C:\Docs\Me\"
call echo Searching in: %currPath%
for %%f in (%currPath%*.doc*) do (
findstr /s /m /I /c:%searchStr% "%%f"
)
set /a x+=1
GOTO :Loop1
)
I have a requirement where I need to increment the variable and store a value into that. For example: Suppose Initially variable Batch1 has value 1000. Now i need to dynamically create subsequent batch variables and store incremental values into those variables e.g. next dynamically created variable should be Batch2 and value it hold should be 1001. Similarly Batch3=1003, Batch4=1004 and so on...
Is this possible in Batch scripting?
You could do this with a method:
#echo off
Rem Start Code
goto :start
:Update_Method
if "%1"=="" goto :eof
if "%2"=="" goto :eof
if "%3"=="" goto :eof
setlocal enabledelayedexpansion
set base=%1
set /a start=%2
set /a end=%3
for /l %%a in (1,1,%end%) do (set /a !base!%%a=!start!+%%a-1)
set base=
set start=
set end=
goto :eof
:start
Rem Start Rest of Code
And that should do what you want. Simply use as:
call Update_Method Batch 1000 10
And that will create:
Batch1=1000
Batch2=1001
Batch3=1002
...
Batch10=1009
Call it whenever you want to "dynamically" change the values.
I still have to test this, but it doesn't seem faulty.
Mona
#echo off
setlocal
for /l %%a in (1 2 50) do call :incrementalSet batch %%a
set batch
endlocal
exit /b
:incrementalSet basename value
setlocal enableextensions enabledelayedexpansion
set "last=0"
:: if the name of the variable can collide with something in the environment,
:: the following line should be used. If not, it is an unnecessary overhead
:: for /f "tokens=1 delims==" %%y in ('set %~1 2^>nul^|findstr /r /b /c:"%~1[0-9][0-9]*="') do (
:: if the base name does not contain numbers, the loop can be reduced to
:: for /f "tokens=1 delims=%~1=" %%y in ('set %~1 2^>nul') do if %%y gtr !last! set "last=%%y"
for /f "tokens=1 delims==" %%y in ('set %~1 2^>nul') do (
set "test=%%y"
set "test=!test:*%~1=!"
if defined test if !test! gtr !last! set "last=!test!"
)
set /a "last+=1"
endlocal & set "%~1%last%=%~2" & exit /b
I made this code
dir /B /S %RepToRead% > %FileName%
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo %z%
echo %%a
)
echo %%a is working fine but echo %z% returns "echo disabled".
I need to set a %z% because I want to split the variable like %z:~7%
Any ideas?
There are two methods to setting and using variables within for loops and parentheses scope.
setlocal enabledelayedexpansion see setlocal /? for help. This only works on XP/2000 or newer versions of Windows.
then use !variable! instead of %variable% inside the loop...
Create a batch function using batch goto labels :Label.
Example:
for /F "tokens=*" %%a in ('type %FileName%') do call :Foo %%a
goto End
:Foo
set z=%1
echo %z%
echo %1
goto :eof
:End
Batch functions are very useful mechanism.
You probably want SETLOCAL ENABLEDELAYEDEXPANSION. See https://devblogs.microsoft.com/oldnewthing/20060823-00/?p=29993 for details.
Basically: Normal %variables% are expanded right aftercmd.exe reads the command. In your case the "command" is the whole
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo %z%
echo %%a
)
loop. At that point z has no value yet, so echo %z% turns into echo. Then the loop is executed and z is set, but its value isn't used anymore.
SETLOCAL ENABLEDELAYEDEXPANSION enables an additional syntax, !variable!. This also expands variables but it only does so right before each (sub-)command is executed.
SETLOCAL ENABLEDELAYEDEXPANSION
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo !z!
echo %%a
)
This gives you the current value of z each time the echo runs.
I struggeld for many hours on this.
This is my loop to register command line vars.
Example : Register.bat /param1:value1 /param2:value2
What is does, is loop all the commandline params,
and that set the variable with the proper name to the value.
After that, you can just use
set value=!param1!
set value2=!param2!
regardless the sequence the params are given. (so called named parameters).
Note the !<>!, instead of the %<>%.
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%P IN (%*) DO (
call :processParam %%P
)
goto:End
:processParam [%1 - param]
#echo "processparam : %1"
FOR /F "tokens=1,2 delims=:" %%G IN ("%1") DO (
#echo a,b %%G %%H
set nameWithSlash=%%G
set name=!nameWithSlash:~1!
#echo n=!name!
set value=%%H
set !name!=!value!
)
goto :eof
:End
Simple example of batch code using %var%, !var!, and %%.
In this example code, focus here is that we want to capture a start time using the built in variable TIME (using time because it always changes automatically):
Code:
#echo off
setlocal enabledelayedexpansion
SET "SERVICES_LIST=MMS ARSM MMS2"
SET START=%TIME%
SET "LAST_SERVICE="
for %%A in (%SERVICES_LIST%) do (
SET START=!TIME!
CALL :SOME_FUNCTION %%A
SET "LAST_SERVICE=%%A"
ping -n 5 127.0.0.1 > NUL
SET OTHER=!START!
if !OTHER! EQU !START! (
echo !OTHER! is equal to !START! as expected
) ELSE (
echo NOTHING
)
)
ECHO Last service run was %LAST_SERVICE%
:: Function declared like this
:SOME_FUNCTION
echo Running: %1
EXIT /B 0
Comments on code:
Use enabledelayedexpansion
The first three SET lines are typical
uses of the SET command, use this most of the time.
The next line is a for loop, must use %%A for iteration, then %%B if a loop inside it
etc.. You can not use long variable names.
To access a changed variable such as the time variable, you must use !! or set with !! (have enableddelayexpansion enabled).
When looping in for loop each iteration is accessed as the %%A variable.
The code in the for loop is point out the various ways to set a variable. Looking at 'SET OTHER=!START!', if you were to change to SET OTHER=%START% you will see why !! is needed. (hint: you will see NOTHING) output.
In short !! is more likely needed inside of loops, %var% in general, %% always a for loop.
Further reading
Use the following links to determine why in more detail:
Difference between %variable% and !variable! in batch file
Variable usage in batch file
To expand on the answer I came here to get a better understanding so I wrote this that can explain it and helped me too.
It has the setlocal DisableDelayedExpansion in there so you can locally set this as you wish between the setlocal EnableDelayedExpansion and it.
#echo off
title %~nx0
for /f "tokens=*" %%A in ("Some Thing") do (
setlocal EnableDelayedExpansion
set z=%%A
echo !z! Echoing the assigned variable in setlocal scope.
echo %%A Echoing the variable in local scope.
setlocal DisableDelayedExpansion
echo !z! &rem !z! Neither of these now work, which makes sense.
echo %z% &rem ECHO is off. Neither of these now work, which makes sense.
echo %%A Echoing the variable in its local scope, will always work.
)
set list = a1-2019 a3-2018 a4-2017
setlocal enabledelayedexpansion
set backup=
set bb1=
for /d %%d in (%list%) do (
set td=%%d
set x=!td!
set y=!td!
set y=!y:~-4!
if !y! gtr !bb1! (
set bb1=!y!
set backup=!x!
)
)
rem: backup will be 2019
echo %backup%
Try this:
setlocal EnableDelayedExpansion
...
for /F "tokens=*" %%a in ('type %FileName%') do (
set z=%%a
echo !z!
echo %%a
)
You can use a macro if you access a variable outside the scope
#echo off
::Define macro
set "sset=set"
for /l %%a in (1,1,4) do (
::set in loop
%sset% /a "x[%%a]=%%a*%%a"
if %%a equ 4 (
:: set in condition
%sset% "x[%%a]=x Condition"
%sset% "y=y Condition"
)
)
echo x1=%x[1]% x2=%x[2]% x3=%x[3]% x4=%x[4]% y=%y%
:: Bonus. enableDelayedExpansion used to access massive from the loop
setlocal enableDelayedExpansion
echo Echo from the loop
for /l %%a in (1,1,4) do (
::echo in one line - echo|set /p =
echo|set /p "=x%%a=!x[%%a]! "
if %%a equ 4 echo y=%y%
)
pause
I know this isn't what's asked but I benefited from this method, when trying to set a variable within a "loop". Uses an array. Alternative implementation option.
SETLOCAL ENABLEDELAYEDEXPANSION
...
set Services[0]=SERVICE1
set Services[1]=SERVICE2
set Services[2]=SERVICE3
set "i=0"
:ServicesLoop
if defined Services[%i%] (
set SERVICE=!Services[%i%]!
echo CurrentService: !SERVICE!
set /a "i+=1"
GOTO :ServicesLoop
)
The following should work:
setlocal EnableDelayedExpansion
for /F "tokens=*" %%a in ('type %FileName%') do (
set "z=%%a"
echo %z%
echo %%a
)
Here is my .bat suffering from the adversity. Lets name it b.bat.
set loopnum=%1
set url=%2
del "%TEMP%\selectortemp.txt"
del "%TEMP%\selectortemp2.txt"
for /r %loopnum% %%i in (\*.*) do echo %%~ni%%~xi>>"%TEMP%\selectortemp.txt"
echo %loopnum%
pause
set count=0
for /f "usebackq delims=" %%a in (%TEMP%\selectortemp.txt) do set /a count+=1
set /a count2=1
:looping
for /f "tokens=1,2 delims==" %%a in (%config%) do (if %%a==url set url=%%b)
set /p firstline=<"%TEMP%\selectortemp.txt"
del "%url%\%firstline%"
echo "%firstline%"
pause
for /f "skip=1 tokens=*" %%A in (%TEMP%\selectortemp.txt) do echo %%A>>"%TEMP%\selectortemp2.txt"
del "%TEMP%\selectortemp.txt"
rename "%TEMP%\selectortemp2.txt" "selectortemp.txt"
if %count2%==%count% goto endlooping
set /a count2+=1
goto looping
:endlooping
At first, I call it by this:
for /l %%i in (0,1,3) do (call b.bat %%i C:\testing)
You are not very specific with your question.
I asume that you mean that your variables lose their content in the for loops.
You need to write !a! instead of %a%. But you can't do this with the variable used in the for loop. !!a is not possible.
Be sure to enable delayed expansion.
Here's some information about enabledelayedexpansion: SS64
I am referring to below threat Batch files: How to read a file?. For retrieving the line by line from a text file. I am using the below script:
#echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ paths.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
echo !var!
ENDLOCAL
)
Code is working fine! The values in !var! can not assign to any variable. :( I struct there, Please anyone help to read line by line and I wish to assign to some variable and want to manipulate that variable. Please help to solve this situation.
Update:
#ECHO off
CLS
SET PROJ_DIR=D:\workspace\proj
SET PROMO_DIR=D:\TEST
SET SOURCE_CODE=\Source Code
SETLOCAL DisableDelayedExpansion
for /f %%a in (paths.txt) do (
SET "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
set FILE_PATH=!var://www.domain.com/path/dir=!
SET FILE_PATH=!FILE_PATH:/=\!
SET PROMO_FILE_PATH=!PROMO_DIR!!SOURCE_CODE!!FILE_PATH!
FOR %%i IN ("!PROMO_FILE_PATH!") DO SET FOLDER_PATH=%%~dpi
FOR %%i IN ("!PROMO_FILE_PATH!") DO SET FILE_NAME=%%~nxi
IF EXIST "!FOLDER_PATH!" GOTO F3
MKDIR "!FOLDER_PATH!"
:F3
IF NOT EXIST "!PROJ_DIR!!FILE_PATH!" GOTO F4
COPY "!PROJ_DIR!!FILE_PATH!" "!FOLDER_PATH!"
:F4
ECHO Cannot find the file under "!PROJ_DIR!!FILE_PATH!"
ENDLOCAL
)
SET CLOSE_CONFIRM=
SET /P CLOSE_CONFIRM=Press any key to close the window...%=%
paths.txt
//www.domain.com/path/dir/dir1/dir2/file1.txt
//www.domain.com/path/dir/dir1/dir2/file2.txt
//www.domain.com/path/dir/dir1/dir2/file3.txt
//www.domain.com/path/dir/dir1/dir2/file4.txt
//www.domain.com/path/dir/dir1/dir3/file1.txt
Command Output
1 file(s) copied.
Cannot find the file under "D:\workspace\proj\dir1\dir2\file1.txt"
1 file(s) copied.
Cannot find the file under "D:\workspace\proj\dir1\dir2\file2.txt"
Press any key to close the window...
thanks..
The key is the delayed expansion, expand your variables inside of parenthesis always with ! not with %.
A sample that changes X with Y
#echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ paths.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
set "myVar=!var!"
set "myVar=!myVar:X=Y!"
echo X replaced with Y =!myVar!
ENDLOCAL
)
In your updated version the goto :label stops the for-loop immediatly
Better rewrite it to IF-Blocks
IF NOT EXIST "!FOLDER_PATH!" (
MKDIR "!FOLDER_PATH!"
)
IF EXIST "!PROJ_DIR!!FILE_PATH!" (
COPY "!PROJ_DIR!!FILE_PATH!" "!FOLDER_PATH!"
) ELSE
(
ECHO Cannot find the file under "!PROJ_DIR!!FILE_PATH!"
)
The other answers here cover the tricky bits of delayed expansion in this code. I want to add that you can often avoid most delayed expansion problems by rolling the parentheses out into a subroutine.
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ paths.txt"`) do call :HandlePath %%a
goto :eof
================
:HandlePath
set "var=%*"
set "var=%var:*:=%"
echo %var%
goto :eof
I find this code easier to maintain because each line is parsed an executed exactly when you would expect.
If you want to read each line and manipulate it:
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=*" %%a IN (paths.txt) DO (
set var=%%a
ECHO %var%
PAUSE
)
ENDLOCAL
If you are trying to search a string from a file and manipulate it:
SETLOCAL EnableDelayedExpansion
FOR /F "tokens=* usebackq" %%a IN (`FIND /I 'string to search for' "C:\folder\paths.txt"`) DO (
set var=%%a
ECHO %var%
PAUSE
)
ENDLOCAL
If you are trying to search a string and manipulate each word in the string:
SETLOCAL EnableDelayedExpansion
FOR /F "usebackq tokens=1-999 delims= " %%a IN (`FIND /I 'string to search for' "C:\folder\paths.txt"`) DO (
REM %%a = first word %%b = second word etc. through the alphabet
set var1=%%a%%b%%c
set var2=%%d
ser var3=%%e
ECHO %var1% %var2% %var3%
PAUSE
)
ENDLOCAL
This works for me:
#echo off
SETLOCAL EnableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ paths.txt"`) do (
set var=%%a
set var=!var:*:=!
echo !var!
)
ENDLOCAL