98percentmonkey
98percentmonkey

Reputation: 555

Variable Scope - access variable outside for-loop - Windows Batch

How can I access the variable !processid! outside the for loop? I can't get it to work

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SETLOCAL 

FOR /F "tokens=* skip=1 delims=" %%a in ('"wmic PROCESS WHERE "CommandLine LIKE '%%scanforstring%%' AND NOT CommandLine LIKE '%%WMIC%%'" get processid"') do (    
set prozessid=%%a
echo !prozessid!
)

echo !prozessid!

PAUSE
endlocal

Upvotes: 1

Views: 3033

Answers (1)

MC ND
MC ND

Reputation: 70923

The problem with your code is that the output from the wmic command includes ending lines that will overwrite the retrieved process id. You can assign the variable only when it has no value

set "prozessid="
for /f ...... do (
    if not defined prozessid (
        set "prozessid=%%a"
        echo !prozessid!
    )
)

Or you can filter the output of the wmic command to only process the correct lines

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /F "usebackq tokens=2 delims==" %%a in (`
    wmic PROCESS WHERE " 
        CommandLine LIKE '%%scanforstring%%' 
        AND NOT CommandLine LIKE '%%WMIC%%'
    " get processid /value
`) do (    
    set prozessid=%%a
    echo 1 - !prozessid!
)

echo 2 - !prozessid!

PAUSE
endlocal

Changes made:

1 - Changed wmic query to use /value so we get an output in the format key=value

2 - Changed for /f options to use the equal sign as delimiter and retrieve only the second token in the line, so only the line with value is processed and %%a will hold the pid

3 - Just cosmetic, changed for /f to use usebackq and changed the quoting in the wmic command

Upvotes: 1

Related Questions