arraysbatch-filevariableslogin-scriptnet-use

How does one assign a drive letter using an array variable in a batch file?


I'm trying to create a login script that uses an array to loop through a set of letters. I've coupled this with adding a counter to move through the array. When using the net use command, I get an error saying the network name can not be found. The end goal is to have the drive letters be listed as A, B, H, I, and so on as needed. I'm sure my syntax is wrong but I can't find an answer.

If I manually substitute the variable with a drive letter I don't get the error. The machine is running Windows Server 2016.

@echo off
set letter[1]="A"
set letter[2]="B"
set letter[3]="H"
set letter[4]="I"
set letter[5]="J"
set letter[6]="K"
set letter[7]="L"
set letter[8]="M"
set letter[9]="N"
set letter[10]="O"
set letter[11]="P"
set letter[12]="Q"
set letter[13]="R"
set letter[14]="S"
set letter[15]="T"

set /A counter=1


ifmember "domain users"
if %errorlevel% == 1 (
net use %%letter[%counter%]%%: \\server\shares
set /A counter+=1
echo "Pass"
)

I expected the output to map the folder to a new drive but instead get "System error 67 has occurred The network name cannot be found."


Solution

  • As you need delayed expansion anyway,

    you could set your array more efficiently with self expanding code.

    :: Q:\Test\2019\06\03\SO_56433581.cmd
    
    @Echo off&SetLocal EnableDelayedExpansion
    Set i=0&Set "letter= A B H I J K L M N O P Q R S T"
    Set "letter=%letter: ="&Set /a i+=1&Set "letter[!i!]=%"
    :: set letter
    set /A counter=1
    ifmember "domain users"
    if %errorlevel% == 1 (
        net use !letter[%counter%]!: \\server\sharesset /A counter+=1
        echo "Pass"
    )
    

    Just for completeness, the code stemmed from a MonthName expansion

    Rem Set MonthName[01..12] to short English month names
    Set i=100&Set "MonthName= Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
    Set "MonthName=%MonthName: ="&Set /a i+=1&Set "MonthName[!i:~-2!]=%"
    Set MonthName