IF statement in batch causing issues. Works when ran individually?

前端 未结 2 1676
闹比i
闹比i 2021-01-24 00:46

At work I set up several computers a day for new users. I\'m using a batch file that gives 3 options: 1. Add new user 2. Change PC name 3. Both They all work great when ran from

2条回答
  •  春和景丽
    2021-01-24 00:55

    When the cmd parser reads a line or a block of lines (the code inside the parenthesis), all variable reads are replaced with the value inside the variable before starting to execute the code. If the execution of the code in the block changes the value of the variable, this value can not be seen from inside the same block, as the read operation on the variable does not exist, as it was replaced with the value in the variable.

    This same behaviour is seen in lines where several commands are concatenated with &. The line is fully parsed and then executed. If the first commands change the value of a variable, the later commands can not use this changed value because the read operation replace.

    To solve it, you need to enable delayed expansion, and, where needed, change the syntax from %var% to !var!, indicating to the parser that the read operation needs to be delayed until the execution of the command.

    setlocal enabledelayedexpansion
    ....
    if "%choose%"=="1" (
        set "user="
        set /p "user=Enter Username, then press Enter to create new user with default password:"
        if defined user net user "!user!" LSCpass14 /add
    )
    ....
    

    The rest of the blocks have the same problem.

提交回复
热议问题