'if errorlevel' statement when in 'for findstr' loop - windows

I have been unsuccessful getting the following to work. Everything works until I try to get the results of the 'findstr' in the 'for' loop. Maybe there is a better way of doing this: look for %subnet% in the masters.csv file. If it finds it, set the MSS variable to the resulting value from the 'for'. If it does not find a value, it will assign a static value (orphan). Thanks in advance for any help!!
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip% > ipaddress.txt
pause
for /F "tokens=1-3 delims=." %%a in ("%ip%") do set FirstThreeOctets=%%a.%%b.%%c
#REM echo First three: %FirstThreeOctets%
#echo off
setlocal
set subnet=%FirstThreeOctets%
echo %subnet%
for /f "tokens=2 delims=," %%A in ('findstr /r "^%subnet%," "\\server\APPS\appname\updates\masters.csv"') do goto OrphanCheck
#REM if errorlevel ==1 goto Orphan do set MSS=%%A
#REM echo %MSS%
#REM goto 64installcheck
:OrphanCheck
if errorlevel==1 goto Orphan
Goto NoOrphan
:NoOrphan
set MSS=%%A
Goto 64installcheck
:Orphan
set MSS=ORPHAN
echo %MSS%
pause

When you run
for /f "tokens=2 delims=," %%A in (
'findstr /r "^%subnet%," "\\server\APPS\appname\updates\masters.csv"'
) do goto OrphanCheck
two things can happen.
If findstr does not find the string, code in for loop is not executed and the next line is reached, but this line does not have access to the errorlevel generated by the findstr, it sees the errorlevel (?) of the for command.
If findstr finds the string, the goto is executed but the same scenario happens.
When the line that checks the error level is reached, another problem raises
if errorlevel==1
is a valid construct, but it does not do what it seams. It is testing if the string errorlevel is equal to the string 1. The correct sintax should be
if errorlevel 1 ....
or
if %errorlevel%==1
but as indicated, when the line is reached the errorlevel will not reflect the error of the findstr command.
And three lines later the next error.
set MSS=%%A
Once the for command has ended, its replaceable parameter does not have any value.
For a simplified version of your code
for /f "tokens=3-6 delims=.: " %%a in ('ipconfig ^| find "IPv4"') do (
set "ip=%%a.%%b.%%c.%%d"
set "subnet=%%a.%%b.%%c"
)
>"ipaddress.txt" echo %ip%
for /f "tokens=2 delims=," %%a in (
'findstr /b /c:"%subnet%," "\\server\APPS\appname\updates\masters.csv"'
) do (
set "MSS=%%a"
goto 64installcheck
)
set "MSS=ORPHAN"
echo %MSS%
pause

Related

Single line nested loop

I am experimenting with a single line cmd /c to get an inner loop without branching. (Actually i have the showLines routine which performs the loop.) I know its worst for performance but i want to know if its possible to get it run without quotes. Currently it raises "%G was unexpected at this time" error. So, it needs some correct escaping or expansion of variables.
#echo off
setlocal enableDelayedExpansion
set "param=%~1"
netstat -aonb | findstr /n $ > tmpFile_Content
for /F "tokens=*" %%A in ('type tmpFile_Content ^| findstr /r /c:"%param%" /i') do (
SET line=%%A
for /F "tokens=1 delims=:" %%I in ("!line!") DO (
set /a LineNum=%%I
rem set /a NextLineNum=LineNum+1
)
set /a lineNum=!LineNum!-1
if !lineNum!==0 ( set param="tokens=*" ) else ( set param="tokens=* skip=!lineNum!" )
rem FOLLOWING WORKS FINE in quotes
cmd /q /v:on /c "#echo off && setlocal enableDelayedExpansion && set cnt=2 && for /F %%param%% %%B in (tmpFile_Content) do ( echo %%B && set /a cnt-=1 >nul && if ^!cnt^!==0 exit /b )"
rem Following does not work even though cmd should take the rest of arguments after /c
cmd /q /v:on /c setlocal enableDelayedExpansion && FOR /F "tokens=*" %%C IN ('echo !param!') DO ( for /F %%C %%G in (tmpFile_Content) do ( echo %%G && set /a cnt-^=1 >nul && if ^!cnt^!==0 exit /b ))
rem call :showLines !LineNum!
)
del tmpFile_Content
goto :eof
:showLines
set /a lineNum=%1-1
set cnt=2
for /F "tokens=* skip=%lineNum%" %%B in (tmpFile_Content) do (
echo %%B
set /a cnt-=1
if !cnt!==0 goto exitLoop
)
:exitLoop
exit /b
to construct for loops with variable parameters, you essentially need to define and execute them as a macro. Eg:
#Echo Off & Setlocal ENABLEdelayedExpasnion
Set param="tokens=* delims="
Set "test=string line"
Set For=For /F %param% %%G in ("^!test^!") Do echo %%G
%For%
Of course you could go even further, and build the entire for loop with another for loop macro on the fly.
UPDATE:
Method for defining conditional concatenation of commands now exampled
Syntax simplified to allow the same usage form for regular expansion and within codeblocks by having the constructor macro call a subroutine to expand the new for loop once it's constructed.
delayed concatenation variable usage simplified to avoid the escaping requirement
#Echo off
::: { Macro Definition
Setlocal DisabledelayedExpansion
(set \n=^^^
%= This creates an escaped Line Feed - DO NOT ALTER =%
)
::: [ For Loop Constructor macro. ] For advanced programmers who need to use dynamic for loop options during code blocks.
::: - usage: %n.For%{For loop options}{variable set}{For Metavariable}{commands to execute}
::: - use delayed !and! variable to construct concatenated commands in the new for loop.
Set n.For=For %%n in (1 2) Do If %%n==2 (%\n%
Set FOR=%\n%
For /F "tokens=1,2,3,4 Delims={}" %%1 in ("!mac.in!") Do (%\n%
Set "FOR=For /F %%1 %%3 in ("!%%2!") Do (%%~4)"%\n%
)%\n%
Call :Exc.For%\n%
)Else Set mac.in=
Set "and.=&&"
Set "and=!and.!"
::: } End macro definition.
Setlocal EnableDelayedExpansion& rem // required to expand n.For constructor macro
::: - Usage examples:
Set "example=is a string line"
%n.For%{"tokens=* delims="}{example}{%%G}{Echo/%%~G}
%n.For%{"tokens=1,2,3,4 delims= "}{example}{%%G}{"Echo/%%~J %%~G %%~H %%~I !and! Echo/%%~I %%~G %%~H %%~J"}
Set "example2=Code block example"
For %%a in (1 2 3) do (
%n.For%{"Tokens=%%a Delims= "}{example2}{%%I}{"For /L %%# in (1 1 4) Do (Set %%I[%%#]=%%a%%#) !and! Set %%I[%%#]"}
)
Pause > Nul
Goto :EOF
:Exc.For
%FOR%
Exit /B
Example output:
is a string line
line is a string
string is a line
Code[1]=11
Code[2]=12
Code[3]=13
Code[4]=14
block[1]=21
block[2]=22
block[3]=23
block[4]=24
example[1]=31
example[2]=32
example[3]=33
example[4]=34
Finally, i came up with following to execute code given in string for anyone interested experimentally and may be for some insight about escaping and expansion.
I use macro instead of cmd which will be much more faster i think(not sure because its said that "call" also causes launch of cmd).
So, it is a simple one-liner without a lot of extra code. But things easily become complicated and when extra escaping and special characters used then #T3RR0R's macro routine would be a necessity.
#echo off
setlocal EnableDelayedExpansion
set "param=%~1"
netstat -aonb | findstr /n $ > tmpFile_Content
for /F "tokens=*" %%A in ('type tmpFile_Content ^| findstr /r /c:"%param%" /i') do (
SET line=%%A
for /F "tokens=1 delims=:" %%I in ("!line!") DO (
set /a LineNum=%%I
rem set /a NextLineNum=LineNum+1
)
set /a lineNum=!LineNum!-1
rem CORRECT QUOTING
if !lineNum!==0 ( set "param="tokens=*"" ) else ( set "param="tokens=* skip=!lineNum!"" )
rem FOLLOWING WORKS FINE in quotes
rem cmd /q /v:on /c "set cnt=2 && for /F ^!param^! %%B in (tmpFile_Content) do ( echo %%B && set /a cnt-=1 >nul && if ^!cnt^!==0 exit /b )"
rem For reading !cnt! use !x!cnt!x!.
rem Only one extra variable used, and in routine its replaced with !(exclamation) for our "cnt" variable.
set "x=^!x^!"
call :ExecCode "set cnt=2 && for /F ^!param^! %%%%B in (tmpFile_Content) do (echo %%%%B && set /a cnt=!x!cnt!x!-1 >nul && if !x!cnt!x!==0 (exit /b) )"
rem call :showLines !LineNum!
)
del tmpFile_Content
goto :eof
:ExecCode
setlocal
rem Replace with exclamation for variable
set "x=^!"
set "s=%~1"
%s%
endlocal
exit /b
:showLines
set /a lineNum=%1-1
set cnt=2
for /F "tokens=* skip=%lineNum%" %%B in (tmpFile_Content) do (
echo %%B
set /a cnt-=1
if !cnt!==0 goto exitLoop
)
:exitLoop
exit /b

How to remove names from a list in batch

I'm using windows bath, I have a list of names that I can add to but I don't know how to remove a name from the list.
So far my code is:
#echo off
setlocal enabledelayedexpansion
set allchoices=123456789
set "names=Bob,Steven,Harry"
set amount=6 ::max limit of list
set list=0
:start
::echoes a list of all names in the list
for /l %%i in (1; 1; %amount%) do (
call :sub %%i
)
goto check
:sub
for /f "tokens=%1 delims=," %%a in ("%names%") do (
echo %%i. %%a
set /a list=list+1
)
goto :eof
:check
::Remove a name from the list
choice /c !allchoices:~0,%list%! /m "What name do you want to remove?"
if errorlevel 3 (
for /f "tokens=3 delims=," %%a in ("%names%") do (
echo you have choosen to remove %%a
::remove third name in the list
goto start
)
)
if errorlevel 2 ::remove second name in the list
if errorlevel 1 ::remove first name in the list
I've tried using del but that turns out to delete a file in your folder.
I've tried renaming a specific name using set name[%%a]="" but that did nothing.
Any ideas?
Have a look at this example. There are many ways.
#echo off
setlocal enabledelayedexpansion
set names="Bob","Steven","Harry"
for %%i in (%names%) do (
set /a num+=1
set "!num!=%%~i"
)
for /l %%a in (1,1,%num%) do (
set choices=!choices!%%a
echo !num!.!%%a!
)
choice /c 123 /m "please select name to remove"
for /l %%a in (1,1,%num%) do if not "!%%a!"=="!%errorlevel%!" set new_names=!new_names! !%%~a!
echo %new_names:~1%
It can be done without the last for loop as well.. but I opted for it.
Here is some example code, for you to run, and then try to comprehend, I hope it helps rather than confuses:
#Echo Off
SetLocal EnableDelayedExpansion
For /F "Delims==" %%A In ('Set # 2^>NUL') Do Set "%%A="
Set "i=0"
For /F "Delims=:" %%A In ('FindStr "^::" "%~f0" 2^>NUL') Do (
Set /A i+=1
Set "#!i!=%%A"
Echo= !i!. %%A
)
:Ask
Set # 1>NUL 2>&1
If ErrorLevel 1 Echo= Empty names list&Timeout 3 1>NUL&Exit /B
Echo=&Set /P "Option= Choose a name to remove>"
Set #|Findstr "^#%Option%=" 1>NUL||GoTo :Ask
Set "Name=!#%Option%!"
Echo= You've chosen to remove "%Name%"
Timeout 2 1>NUL
Set "#%Option%="
ClS
For /F "Tokens=1*Delims=#=" %%A In ('Set # 2^>NUL') Do Echo= %%A. %%B
GoTo Ask
::Alan
::Beth
::Cleo
::Dale
::Eric
::Faye
::Greg
::Hugh
::Inga
Important note:Please ensure, before saving the above content as a Windows Command Script, that there is a line return, (blank line), at the end.

The ^ gets doubled when sending string as parameter to function in batch script

This is my code:
set var1="`netsh int ipv4 show interface ^| findstr /I Network`"
call:GetEles %var1%
goto:eof
:GetEles
for /F "tokens=1 usebackq" %%F IN (%~1) do echo %%F
goto:eof
When I check the command while it is running, the ^ becomes doubled inside function :GetEles:
for /F "token=1 usebackq" %%F IN (`netsh int ipv4 show interface ^^| findstr /I Network`) do echo %%F
That doubled ^ makes my script failing, how can I solve it?
As others already described, this is a nasty "feature" of the call command.
There are several options to work around that:
Simply undo the caret doubling in the sub-routine:
#echo off
set "VAR=caret^symbol"
call :SUB "%VAR%"
exit /B
:SUB
set "ARG=%~1"
echo Argument: "%ARG:^^=^%"
exit /B
call introduces a second parsing phase, so let the second one expand the variable:
#echo off
set "VAR=caret^symbol"
call :SUB "%%VAR%%"
exit /B
:SUB
echo Argument: "%~1"
exit /B
Pass the value by reference (so the variable name) rather than by value:
#echo off
set "VAR=caret^symbol"
call :SUB VAR
exit /B
:SUB
setlocal EnableDelayedExpansion
echo Argument: "!%~1!"
endlocal
exit /B
Do not pass the variable value to the sub-routine, read the (global) variable there instead:
#echo off
set "VAR=caret^symbol"
call :SUB
exit /B
:SUB
echo Argument: "%VAR%"
exit /B
Read Buggy behaviour when using CALL:
Redirection with & | <> does not work as expected.
If the CALL command contains a caret character within a quoted string
"test^ing", the carets will be doubled.
Try following code snippet:
#echo off
SETLOCAL EnableExtensions
set "var1=`netsh int ipv4 show interface ^| findstr /I "Network"`"
call:GetEles "%var1%"
goto:eof
:GetEles
echo variable "%var1%"
echo parameter "%~1"
for /F "tokens=1 usebackq" %%F IN (%var1%) do echo %%F
goto:eof
Output:
d:\bat> D:\bat\SO\41769803.bat
variable "`netsh int ipv4 show interface ^| findstr /I "Network"`"
parameter "`netsh int ipv4 show interface ^^| findstr /I "Network"`"
Try it like this, (the call will not expand the %var1% to a point which will expose the poison character).
set "var1='netsh int ipv4 show interface ^| findstr /I Network'"
call:GetEles "%%var1%%"
goto:eof
:GetEles
for /F %%F IN (%~1) do echo %%F
goto:eof
You will note that tokens=1 wasn't needed and neither was usebackq

How to create a unique output filename for Windows Script?

I am trying to create a windows script that should generate this kind of filename everytime I run it: filename1, filename2, filename3 and so on. Here is what I have so far:
(
#echo off
wmic logicaldisk get size,freespace,caption
) > disk.txt
I hope you can help me. Thanks!!
:: make a tempfile
:maketemp
SET "tempfile=%temp%\%random%"
IF EXIST "%tempfile%*" (GOTO maketemp) ELSE (ECHO.>"%tempfile%a")
You now have any number of filenames available.
%tempfile%a exists and is empty, but %tempfile%anythingelse should be available for use.
#ECHO OFF
SETLOCAL
SET "basename=filename"
SET /a outname=0
:genloop
SET /a outname+=1
IF EXIST "%basename% %outname%.txt" GOTO genloop
SET "outname=%basename% %outname%.txt"
ECHO %outname%
GOTO :EOF
Ah - increment the destination filename on each run. This should do that. It's not actually creating a file - you'd need to create the file %outname% each time to have it increment...
(the space between %basename% and %outname% is optional, of course - omit it if desired.)
edited to include .txt
This will give you up to 1000 filenames but you can go higher, up to 2 Billion, but the higher you go the longer the delay will be before it picks a filename.
#echo off
for /L %%a in (1,1,1000) do if not defined filename if not exist "filename%%a.txt" set "filename=filename%%a.txt"
(
wmic logicaldisk get size,freespace,caption
) > "%filename%"
#echo off
setlocal enableextensions
call :getNextFilename "filename*.txt" nextFilename
echo %nextFilename%
echo test > "%nextFilename%"
call :getNextFilename "%cd%\filename*.txt" nextFilename
echo %nextFilename%
echo test > "%nextFilename%"
endlocal
exit /b
:getNextFilename whatToSearch returnVariable
setlocal enableextensions enabledelayedexpansion
for /f %%a in ("$\%~1"
) do for /f "tokens=1,* delims=*" %%b in ("%%~nxa"
) do ( set "left=%%b" & set "right=%%c" )
set "max=0"
for %%a in ("%~1"
) do for /f "tokens=1 delims=%left%%right% " %%b in ("%%~nxa"
) do for /f "tokens=* delims=0 " %%c in ("0%%~b"
) do if %%~c geq !max! set /a "max=%%c+1"
endlocal & set "%~2=%~dp1%left%%max%%right%" & exit /b
This should find the next file in sequence independently of the existence of holes in the numeration of the files. A path can be included or omitted. The * will be used as the placeholder for the numeration. BUT this will not work if files or included paths have "problematic" characters.
If the date/time of creation of the file can be considered, then this version can be optimized as
:getNextFilename whatToSearch returnVariable
setlocal enableextensions disabledelayedexpansion
for /f %%a in ("$\%~1"
) do for /f "tokens=1,* delims=*?" %%b in ("%%~nxa"
) do ( set "left=%%b" & set "right=%%c" )
set "max=0"
for /f "delims=" %%a in ('dir /tc /o-d /b "%~1" 2^>nul'
) do for /f "tokens=1 delims=%left%%right% " %%b in ("%%~nxa"
) do for /f "tokens=* delims=0 " %%c in ("0%%~b"
) do set /a "max=%%c+1" & goto done
:done
endlocal & set "%~2=%~dp1%left%%max%%right%" & exit /b
that will take the latest created instance of the file set.
I finally figured out where to put the .txt extension. This is from #Magoo's answer but I wanted the file to be a text file so I placed the .txt twice in order for it to work properly.
#ECHO OFF
SETLOCAL
SET "basename=DISK-OUT"
SET /a outname=0
:genloop
SET /a outname+=1
IF EXIST "%basename% %outname%.txt" GOTO genloop
SET "outname=%basename% %outname%.txt"
(
wmic logicaldisk get size,freespace,caption
) > "%outname%"
GOTO :EOF

Reading a text file line by line and storing it in an array using batch script

I want to read a text file and store each line in an array. When I used the code below, "echo %i%" is printing 0 every time and only array[0] value is getting assigned. But in "set n=%i%",n value is assigned as the last incremented I value.Also "#echo !array[%%i]!" is printing like !array[0]! instead of printing the value. Is there any syntax error in the code?
set /A i=0
for /F %%a in (C:\Users\Admin\Documents\url.txt) do (
set /A i+=1
echo %i%
set array[%i%]=%%a
)
set n=%i%
for /L %%i in (0,1,%n%) do #echo !array[%%i]!
Here's a method that is useful at times and very similar to your code:
#echo off
set "file=C:\Users\Admin\Documents\url.txt"
set /A i=0
for /F "usebackq delims=" %%a in ("%file%") do (
set /A i+=1
call echo %%i%%
call set array[%%i%%]=%%a
call set n=%%i%%
)
for /L %%i in (1,1,%n%) do call echo %%array[%%i]%%
#echo off &setlocal enabledelayedexpansion
for /F "delims=" %%a in (C:\Users\Admin\Documents\url.txt) do (
set /A count+=1
set "array[!count!]=%%a"
)
for /L %%i in (1,1,%count%) do echo !array[%%i]!
Inside a code block you need delayed expansion and !variables!.
Read set /? description about environment run-time linking. When you are using %i% inside for - it is pre-expanded before for execution. You need to use !i! instead.
#ECHO OFF
SETLOCAL
FOR /f "tokens=1*delims=:" %%i IN ('findstr /n /r "$" url.txt') DO SET max=%%i&SET array[%%i]=%%j
FOR /l %%i IN (1,1,%max%) DO CALL ECHO(%%array[%%i]%%
GOTO :EOF
provided no line begins ":"

Resources