How To Use FOR Loop To map Network Shares From Different Networks Resources

Mapping network shares from a network is a pretty easy thing to do. The standard command for this in windows is:

net use x: \\{host}\{share} {password} /u:{unsername} /p:{no|yes}


x = drive letter (a-z)

p = persistent (yes means re-map after system restart and no means the opposite)

Assuming you want to automate such action mapping more shares from different networks, you will want to use the FOR loop in a batch script. These steps will show my aproach:


1.) The first thing to do is create and place all your share information (host, share, password, username and drive letters in a file and name the file anything you want. To suite my purpose, I’ll jsut name the file “dat2” without any file extention. The content should look like this:






2.) Create a batch script to disconnect all existing network drives. Let’s name this file “delmap.bat”


REM ======================= Begin Of Script =============================

@echo off

REM Check and disconnect all existing network drives


if exist t: net use /del t: /y

if exist u: net use /del u: /y

if exist v: net use /del v: /y

if exist w: net use /del w: /y


goto :EOF

REM ======================= End Of Script =============================


3.) Now, we can create the main script “NetShare.bat” with the following contents:


REM ======================= Begin Of Script =============================


@echo off

REM To avoid error messages, check and disconnect all existing network drives

REM by calling another batch file named delmap.bat.


call “%~dp0\delmap.bat”

REM To avoid unexpected errors, the system needs to wait 3 seconds after

REM disconnecting all existing drives before re-mapping the network resources.

REM All pre-defined parameters in the file (dat2) will be fetched line by line using

REM the (for) loop. There are 6 columns in the file (dat2) separated by commas (delims).

REM The first is the line numbers (not needed). That is the reason why the tokens is

REM defined from 2-6. The pre-defined variables (hostN, userN, paswd, drive and share) are

REM passed one by one from the ‘sub routine’ (:var) to process the mapping of the drives.


ping -n 3>nul

for /F “tokens=2-6 delims=,” %%g IN (%~dp0dat2) do call :var %%g %%h %%i %%j %%k

goto end


set hostN=%1

set userN=%2

set paswd=%3

set drive=%4

set share=%5

net use %drive%: \\%hostN%\%share% %paswd% /U:%userN% /P:no

goto :EOF



REM ======================= End Of Script =============================




Both files NetShare.bat and delmap.bat are included in the dowload below:


You need to create  your share information (dat2) by following the first step above.

Posted in Windows and tagged , , , , , by with comments disabled.