简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM