Search code examples
batch-filecmdwmic

Batch - Loop through comma delimited string


I'm trying to loop through fields for wmic, whose output then gets written to a text file.

The goal in the end, is to have a tab (or other) delimited file of hardware information. I can't seem to loop past the first command, the execution ends on the first execution of each loop.

Haven't worked much with batch file before, please help me get this sorted out.

::@ECHO OFF

:: Prompt user for computer name
SET /P id="Enter Computer Name: "

::Fetch IP
FOR /F "skip=4 usebackq tokens=2" %%a IN (`nslookup %id%`) DO (
SET ip=%%a
)

::Change working directory to .bat file location
CD %~dp0

::Creates/Clears record.
break > %id%.txt

REM Level 1: Loops through fields to be pulled
FOR /F "tokens=1* delims=," %%c IN ("computersystem get name,computersystem get name,computersystem get name") DO (

    REM Level 2: Pulls value in key=value format, parses value by '=' delimiter
    FOR /F "tokens=2 delims==" %%x IN ('
        wmic %%c /value
    ') DO (
        REM Level 3: Removes line carriage, adds a <tab> character. 
        FOR /f %%z IN ("%%x") DO (
            <nul set /p = %%z
            <nul set /p = " "
        )>> %id%.txt
    )

)

Solution

  • You appear to be using a For /F loop at Level 1: instead of a standard For loop:

    @Echo Off
    CD /D "%~dp0"
    Set /P "ID=Enter Computer Name: "
    For /F "Tokens=2" %%A In ('NSLookUp %ID% 2^>Nul') Do Set "IP=%%A"
    (For %%A In ("ComputerSystem Get Name","ComputerSystem Get Name",
     "ComputerSystem Get Name") Do For /F "Tokens=1* Delims==" %%B In (
        'WMIC %%~A /Value 2^>Nul') Do For /F "Tokens=*" %%D In ("%%~C"
    ) Do <Nul Set /P=%%D    )>"%ID%.txt"
    

    Note:     The whitespace before the final closing parenthesis is a TAB