如何在批处理命令中将“for”循环内的字符串用作变量名

时间:2017-01-09 09:52:25

标签: batch-file

尝试为Windows创建用户管理器类型程序时遇到问题。 在这一点上,我不确定这是否是一个简单或不可能修复,因为我找到修复的所有尝试都是无用的。 (很可能是因为对编程术语的了解很糟糕。)

我正在尝试将一些字符串和“for”循环计数器组合成一个字符串,然后使用结果字符串调用已存储的变量,该变量具有在最终字符串中定义的名称。

计数器应该调用已在本教程的“数组”或数组替代中定义的特定用户:https://www.youtube.com/watch?v=l0ib2kCaVuA&list=PL69BE3BF7D0BB69C4&index=64

如何使字符串 instantUser 像变量 allowed_users [0] 一样?

@echo off
setlocal enabledelayedexpansion

title CP Script

setlocal
:Setup
echo What do you want to do? [#]
echo 1. Fix Users + Groups
echo 2. Configure Firewall + Updates
echo 3. Fix Remote Connection
echo 4. Find Illegal Files
echo 5. Configure Audits
echo 6. Fix Minor - 

set COMMAND=
set /p COMMAND=Type input: %=%

If %COMMAND%==1 goto Account
If %COMMAND%==2 goto Basic
If %COMMAND%==3 goto Remote
If %COMMAND%==4 goto Files
If %COMMAND%==5 goto Audits
If %COMMAND%==6 goto Minor
echo Incorrect input & goto Setup

:Account
    cls
    echo File path to user list-
    set DIRECTORY=
    set /P DIRECTORY=Type input: %=%
    set /p Build=<"%DIRECTORY%"
    cls

    call create_array allowed_users "," "%Build%"

    :: PROBLEM WAS HERE
    set /a "allowed_users_length_main=allowed_users_length-1"
    For /L %%b In (0,1,%allowed_users_length_main%) Do (
        Net User "!allowed_users[%%b]!" /Add
    )
    :: PROBLEM ENDED HERE

    echo.
    goto :Setup

:Basic
:Remote
:Files
:Audits
:Minor
endlocal

goto :eof

1 个答案:

答案 0 :(得分:1)

<强> [实施例]

@Echo Off
SetLocal EnableDelayedExpansion

Set "allowed_users[0]=Johnny Was"
Set "allowed_users[1]=Jimmy Jazz"
Set "allowed_users[2]=Jimmy Jimmy"
Set "allowed_users[3]=Johnny Jewel"

Set/A "allowed_users_length=-1"
For /F %%A In ('Set allowed_users[') Do Set/A "allowed_users_length+=1"

For /L %%b In (0,1,%allowed_users_length%) Do (
    Net User "!allowed_users[%%b]!" /Add
)