0

I am trying to make a CMD batch script that constantly logs IP statistics and puts them in different .txt files, for this I have created 2 arrays, one that contains the names I wish to give to the txt files and other one that contains the ips I wish to ping.

I try to loop the elements in the arrays as names/parameters for different commands on the CMD shell, the part for the .txt names works but I can't get extracting the ip addresses from the corresponding array and passing them to the ping command to work. My code is:

@echo off
set Noms=(bni csc cba lpz oro pnd pts scz trj)
set Dirs=(8.8.8.8 8.8.8.4 8.8.8.4 8.8.8.8 8.8.8.8 8.8.8.4 8.8.8.8 8.8.8.4 8.8.8.8)
rem --------------------------------------------------------------
rem Builds .txts with names in list Noms pinging Addresses in Dirs
rem --------------------------------------------------------------
for %%j in %Noms% do (
set direccion = %Dirs[%%j]%
ping /n 3 %direccion% > c:\log\p0.txt
findstr "Media" c:\log\p0.txt > c:\log\p1.txt
for /f "tokens=3 delims=," %%i in (c:\log\p1.txt) do @echo %%i > c:\log\p2.txt
for /f "tokens=4 delims=<equal> " %%i in (c:\log\p2.txt) do @echo %%i > c:\log\p0.txt
for /f "tokens=1 delims=m" %%i in (c:\log\p0.txt) do (set pingvar=%%i)
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b) 
For /f "tokens=1-3 delims=/:," %%a in ("%TIME%") do (set mytime=%%a:%%b:%%c) 
set totvar=%mydate%     %mytime%    %pingvar%
echo %totvar% > c:\log\%%j.txt
)

I found no mistake in my code, basically I try to put the IP address from the array "Dirs" in the variable "direccion" and then passit as an argument to ping.

Thank you for helping me.

4
  • That's because %Dirs[...]% doesn't exist. Commented Nov 17, 2017 at 1:37
  • Ok, then what would the correct syntax be?? Commented Nov 17, 2017 at 1:49
  • Given you have a predefined set of names and ips I think you should construct your "array" with something like set "Dirs[bni]=8.8.8.8", ..., set "Dirs[trj]=8.8.8.8" Commented Nov 17, 2017 at 1:57
  • That doesn't seem to be working either, closer inspection reveals the output from ping is "Could not find host Dirs[1]", which I guess means the script isn't passing "bni" or "trj" as index for the list or array Commented Nov 17, 2017 at 2:08

1 Answer 1

1

You have to use enable delayed expansion. I'll show a sample code with some of your names

@echo off

setlocal EnableDelayedExpansion

set "names=bni csc cba"
set "Dirs[bni]=1.1.1.1"
set "Dirs[csc]=2.2.2.2"
set "Dirs[cba]=3.3.3.3"

for %%I in (%names%) do (
   echo(Name:%%I, IP:!Dirs[%%I]!
)

The output for the above is:

Name:bni, IP:1.1.1.1
Name:csc, IP:2.2.2.2
Name:cba, IP:3.3.3.3

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.