0

I would like to create a batch file to easily connect to some network drives. I was thinking of using some kind of nested for loop but I'm a bit stuck. So I have two variables:

set drives=F,G,H
set paths=LOCATION01\name1,LOCATION02\name1,LOCATION01\name2

Now I would like to be able to echo them like this: (well, instead of echo it, I will connect the right path to the right drive, but that doesn't matter here)

F -> LOCATION01\name1
G -> LOCATION02\name1
H -> LOCATION01\name2

I'm not sure of how to solve this one. At first I tried something like the following, but that sure didn't work. It just looped through every path for every drive and I just want one path per drive.

FOR %%A IN (%drives%) DO FOR %%B IN (%paths%) DO ECHO %%A %%B

So... Any suggestions? Thanks!

  • 1
    You will of course get all combinations with nested loops, since the inner loop iterates through all its items for *every* single iteration of the outer one. But do you really need to define the drives and paths like this? Could you not use some array-style variables like `set "drive[1]=F"` and `path "dpath[1]=LOCATION01\name1"`, etc.? See also this post: [How to loop through array in batch?](http://stackoverflow.com/q/18462169) – aschipfl Aug 05 '16 at 08:01
  • Are you trying to map network drives to certain drive letters via batch? – sambul35 Aug 05 '16 at 12:06
  • 1
    May I inquire why you are not hard coding three `NET USE` commands? – Squashman Aug 05 '16 at 12:50

1 Answers1

0

Try this:

@echo off  
setlocal enabledelayedexpansion
set drives=F,G,H
set paths=LOCATION01\name1,LOCATION02\name1,LOCATION01\name2
set drivecounter=0
for %%d in (%drives%) do (
  set /a "drivecounter+=1"
  set pathcounter=0
  for %%p in (%paths%) do (
    set /a "pathcounter+=1"
    if /i !drivecounter! == !pathcounter! (
      echo %%d assigned to %%p
    )
  )
)

The code expands on your idea of looping through all drives and all paths but uses variables to keep track of the indexes for each so it can assign the correct path to the current drive being processed.

Filipus
  • 520
  • 4
  • 12