^ Doubles when sending a string as a parameter to a function in a 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 during its launch, ^it becomes double inside the function :GetEles:

for /F "token=1 usebackq" %%F IN (`netsh int ipv4 show interface ^^| findstr /I Network`) do echo %%F

As a result of doubling ^my script error, how can I solve it?

+4
source share
3 answers

As already described, this is an unpleasant "function" callcommand .

There are several options for this:

  • Just cancel the carriage doubling in the routine:

    @echo off
    set "VAR=caret^symbol"
    call :SUB "%VAR%"
    exit /B
    
    :SUB
        set "ARG=%~1"
        echo Argument: "%ARG:^^=^%"
        exit /B
    
  • call introduces the second phase of the parsing, so let the second 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 (this is the name of the variable), and not by value:

    @echo off
    set "VAR=caret^symbol"
    call :SUB VAR
    exit /B
    
    :SUB
        setlocal EnableDelayedExpansion
        echo Argument: "!%~1!"
        endlocal
        exit /B
    
  • , () :

    @echo off
    set "VAR=caret^symbol"
    call :SUB
    exit /B
    
    :SUB
        echo Argument: "%VAR%"
        exit /B
    
+3

CALL:

& | <> , .

CALL "test^ing", .

:

@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

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"`"
+3

Try this, ( callwill not expand %var1%to the point that will display the poison symbol).

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 notice that it is tokens=1not required, and was notusebackq

+2
source

Source: https://habr.com/ru/post/1667387/


All Articles