Executing dynamic code blocks

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Posts: 17
Joined: 12 Jun 2020 10:38

Executing dynamic code blocks

#1 Post by lockedscope » 12 Jun 2020 10:47

In the following experimental code, i could dynamically create *code* blocks with several alternatives.

So, i want to know if it is possible to simplify the Alternative0 with escaping and also those multi-levels of expansions.

Code: Select all

@echo off

call :check_Permissions
if not %errorLevel%==0 exit /b

setlocal enableDelayedExpansion

set "param=%~1"

IF "%param%" == "" GOTO ShowInfo

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 [Alternative0] 
  set "cnt..=0"
  set "cnt.=^!cnt..^!"  
  set "cnt=^!cnt.^!"
  set quot.=^"
  set "quot=^!quot.^!"

  call :myloop "for /F !quot!!param!!quot! %%%%G in (tmpFile_Content) do (echo %%%%G && set /a cnt..=!cnt!+1 >nul && if !cnt!==2 (exit /b) )"
  rem [EndOfAlternative0]

  rem [Alternative1]
  rem FOLLOWING WORKS FINE in quotes
  rem cmd /q /v:on /c "setlocal && set cnt=2 && for /F %%param%% %%B in (tmpFile_Content) do ( echo %%B && set /a cnt-=1 >nul && if ^!cnt^!==0 exit /b )"
  rem [EndOfAlternative1]

  rem [Alternative2]
  rem set cnt=0  
  rem set "xyz=^!cnt^!"
  rem call :myloop "for /F ^!quot^!!param!^!quot^! %%%%G in (tmpFile_Content) do (echo %%%%G && set /a cnt=^!xyz^!+1 >nul && if ^!xyz^!==2 (exit /b) )"
  rem [EndOfAlternative2]
  rem call :showLines !LineNum!


del tmpFile_Content

goto :eof

    net session >nul 2>&1
    if not %errorLevel% == 0 (
        echo Administrator permissions required!
        pause >nul
        exit /b 1
exit /b

  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
  exit /b


echo MySearchPort "string"
echo "string": Port value etc. to search
exit /b


set "str=%~1"

exit /b  
goto :eof

Posts: 1822
Joined: 23 Jun 2013 06:15
Location: Germany

Re: Executing dynamic code blocks

#2 Post by penpen » 15 Jun 2020 03:37

This might help you (untested):

Code: Select all

	set "e=^^^!"
	set "cnt=0"
	set quot=^"

	call :myloop "for /F !quot!!param!!quot! %%%%G in (%~nx0) do (echo(#%%%%G && set /a cnt=cnt+1 >nul && if %%e%%cnt%%e%%==2 (exit /b) )"


Post Reply