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

前端 未结 2 1675
闹比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:59

    Use this code with enclosing all strings in double quotes where needed because of special characters in string.

    @echo off
    setlocal EnableDelayedExpansion
    set /p "choose=Enter your selection here: "
    if "!choose!"=="1" (
       echo Enter user name, then press Enter to create new user with default password.
       set /p "user=User name: "
       %SystemRoot%\system32\net.exe user "!user!" LSCpass14 /add
    ) else if "!choose!"=="2" (
       set /P "pcname=Please enter this computer's LSC Asset Tag number, eg. 1295: "
       %SystemRoot%\system32\reg.exe ADD HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters /v "NV Hostname" /t REG_SZ /d "LSC-!pcname!" /f
       echo You will need to restart your computer for these changes to be applied.
       set /p "reboot=Would you like to restart now? [y/n] "
       if /i "!reboot!"=="y" start %SystemRoot%\system32\shutdown.exe -r -t 00
    ) else if "!choose!"=="3" (
       echo Enter user name, then press Enter to create new user with default password.
       set /p "user=User name: "
       %SystemRoot%\system32\net.exe user "!user!" LSCpass14 /add
       set /P "pcname=Please enter this computer's LSC Asset Tag number, eg. 1295 : "
       %SystemRoot%\system32\reg.exe ADD HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters /v "NV Hostname" /t REG_SZ /d "LSC-!pcname!" /f
       echo You will need to restart your computer for these changes to be applied.
       set /p "reboot=Would you like to restart now? [y/n] "
       if /i "!reboot!"=="y" start %SystemRoot%\system32\shutdown.exe -r -t 00
    )
    endlocal
    

    On last page output in a command prompt window after entering help cmd or cmd /? a list of characters is displayed which requires a string to be enclosed in double quotes. The parentheses and the square brackets belong also to this group of special characters. The batch code demonstrates why () have a special meaning and therefore strings containing them literally require surrounding double quotes.

    And it is necessary to use delayed expansion of the environment variables as explained in help output after entering set /? or help set.

提交回复
热议问题