Domanda

I have a text file with the names of computer names and corresponding static i.p. addresses in the following format.

COMPUTER NAME:PC ADDRESS=154.100.1.1 MASK=255.255.254.0 
COMPUTER NAME:PC2 ADDRESS=100.100.1.1 MASK=255.255.254.0 

I would like to take the values from each line and put them as variables in a batch file for use later. Is this possible? The overall goal is to have the values from this easily edited text file to be used in netsh commands in another batch file.

I've looked around and found ways to take lines of a text file and place them in one variable using the snippet below. However, I do not know how to create multiple variables from one line. If someone could help me with this I'd greatly appreciate it!

@echo o
setlocal enabledelayedexpansion
set Counter=1
for /f %%x in (D:\COMP_T.txt) do (
  set "comp!Counter!=%%x"
  set /a Counter+=1
)
È stato utile?

Soluzione

This should work:

@echo off
setlocal EnableDelayedExpansion
set "Count=1"
for /f "tokens=1,2,3,4,5,6,7 delims==: " %%A in (C:\File.txt) do (
    set "%%A[!Count!]=%%C"
    set "%%D[!Count!]=%%E"
    set "%%F[!Count!]=%%G"
    set /a "Count+=1"
)
:: Call other batch script here.
endlocal

Example Output:

COMPUTER[1]=PC
COMPUTER[2]=PC2
ADDRESS[1]=154.100.1.1
ADDRESS[2]=100.100.1.1
MASK[1]=255.255.254.0
MASK[2]=255.255.254.0

Altri suggerimenti

Here is a solution that avoids the need for delayed expansion. It uses FINDSTR to insert a line number followed by : at the beginning of each line. The search string of "^" is guaranteed to match every line in the file.

The only other issue is to set TOKENS and DELIMS to parse the line properly.

@echo off
setlocal
for /f "tokens=1,4,6,8 delims=:= " %%A in ('findstr /n "^" "d:\comp_t.txt"') do (
  set "comp%%A=%%B"
  set "addr%%A=%%C"
  set "mask%%A=%%D"
  set "counter=%%A"
)

To use the set of variables in another batch file, line by line, just parse the lines as done in other answers here, and call the other batch file with the metavariables.

@echo off
for /f "tokens=1,2,3,4,5,6,7 delims==: " %%a in ('type "File.txt" ') do (
    echo "computer_name=%%c"
    echo "address=%%e"
    echo "mask=%%g"
Call "batch script" "%%c" "%%e" "%%g"
)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top