Marslo
Marslo

Reputation: 3241

Set doesn't work in for + if in bat script, even if set ENABLEDELAYEDEXPANSION

My Script (a.bat):

SETLOCAL ENABLEDELAYEDEXPANSION

if "%1"=="on" (
    FOR /F "tokens=1" %%a in ('netsh interface show interface ^| findstr Local') DO (set lanst=%%a)
    set lanst=%lanst: =%
    echo Local Area Connection: %lanst%

    FOR /F "delims=: tokens=2" %%b in ('netsh wlan show interface ^| findstr SSID ^| findstr /v B') DO (set curwifi=%%b)
    set curwifi=%curwifi: =%
    echo Current Wifi: %curwifi%
)

When I run this script in commandline, seems the set dosen't work in for + if: if+for


But when I remove if-statement, the script is:

SETLOCAL ENABLEDELAYEDEXPANSION
echo %1

    FOR /F "tokens=1" %%a in ('netsh interface show interface ^| findstr Local') DO (set lanst=%%a)
    set lanst=%lanst: =%
    echo Local Area Connection: %lanst%

    FOR /F "delims=: tokens=2" %%b in ('netsh wlan show interface ^| findstr SSID ^| findstr /v B') DO (set curwifi=%%b)
    set curwifi=%curwifi: =%
    echo Current Wifi: %curwifi%

the result shows: only-for

According the output, I found, in the situation of if+for, seems the statement in do() will not be executed. Why's that, and how to fix?

Upvotes: 2

Views: 618

Answers (1)

npocmaka
npocmaka

Reputation: 57252

try with:

SETLOCAL ENABLEDELAYEDEXPANSION

if "%1"=="on" (
    FOR /F "tokens=1" %%a in ('netsh interface show interface ^| findstr Local') DO (
        set lanst=%%a
    )
    set lanst=!lanst: =!
    echo Local Area Connection: !lanst!

    FOR /F "delims=: tokens=2" %%b in ('netsh wlan show interface ^| findstr SSID ^| findstr /v B') DO (
        set curwifi=%%b
    )
    set curwifi=!curwifi: =!
    echo Current Wifi: !curwifi!
)

here's more info about the delayed expansion

Upvotes: 2

Related Questions