IP-Configuration from Batch file

巧了我就是萌 提交于 2019-12-25 02:19:55

问题


@echo off

set /p option=(1) Edit IP (2) Enable DHCP:

if %option%==1 (

set /p IP=New IP-Address:
set /p MASK=New Network Mask:
set /p GATE=New Gateway Address:

netsh interface ip set address name="LAN" static %IP% %MASK% %GATE% 1
)

if %option%==2 (

netsh interface ip set address name="LAN" source=dhcp
)

pause

The DHCP part of the program works just fine. The NIC's name is "LAN". I have tried with and without the 1 paramenter on the set IP. I have also tried with different variable names.

The error I get after entering a valid ipv4 address, a subnetmask and a gateway address is:

Invalid Address Parameter <1>: Must be a valid IPv4-Address


回答1:


Your problem is delayed expansion. All variable reads inside a block of code (code inside parenthesis) are replaced with the value in the variable before the block starts to execute. If a variable is changed inside the block, that new value can not be retrieved, as all reads to variables were replaced with values. To solve, enable delayed expansion and, in variables where delayed read is needed, change %var% sintax with !var! to indicate the parser to delay the read until the time of execution.

@echo off

set /p option=(1) Edit IP (2) Enable DHCP:

if %option%==1 (
    set /p IP=New IP-Address:
    set /p MASK=New Network Mask:
    set /p GATE=New Gateway Address:

    setlocal enabledelayedexpansion
    netsh interface ip set address name="LAN" static !IP! !MASK! !GATE! 1
    endlocal
)

if %option%==2 (
    netsh interface ip set address name="LAN" source=dhcp
)

pause


来源:https://stackoverflow.com/questions/21824179/ip-configuration-from-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!