Change default gateway using vbscript by altering last octet of IP

浪尽此生 提交于 2020-01-14 03:37:08

问题


User is asked to manually input the IP i.e 192.168.0.2 The gateway will then change to 192.168.0.254 The InStrRev() and Left() functions should work just can't quite get it to run.

 Set objWMIService = GetObject( "winmgmts://./root/CIMV2" )
    strQuery = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE MACAddress > ''"
    Set colNetAdapters = objWMIService.ExecQuery _ 
        (strQuery)  

    strIPAddress = Array(InputBox("IP address"))
    strSubnetMask = Array("255.255.255.0") 
    strGateway = Left(strIPAddress, InStrRev(strIPAddress, ".")) & "254"
    strGatewayMetric = Array(1) 

    For Each objNetAdapter in colNetAdapters 
        errEnable = objNetAdapter.EnableStatic(strIPAddress, strSubnetMask) 
        errGateways = objNetAdapter.SetGateways(strGateway, strGatewaymetric) 
        If errEnable = 0 Then 
            WScript.Echo "The IP address has been changed." 
        Else 
            WScript.Echo "The IP address could not be changed." 
        End If 

    next

回答1:


Use Split() to get an array of octets, and change the last one:

>> s = "192.168.0.2"
>> a = Split(s, ".")
>> a(3) = "254"
>> WScript.Echo Join(a, ".")
>>
192.168.0.254



回答2:


Looks like I solved my own problem

Set objWMIService = GetObject( "winmgmts://./root/CIMV2" )
    strQuery = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE MACAddress > ''"
    Set colNetAdapters = objWMIService.ExecQuery _ 
        (strQuery)  

strIPAddress = (InputBox("IP address"))
strSubnetMask = Array("255.255.255.0")
strGateway = Left(strIPAddress, InStrRev(strIPAddress, ".")) & "254"
strIPAddress = Array(strIPAddress)
strGateway = Array(strGateway)
strGatewayMetric = Array(1) 

For Each objNetAdapter in colNetAdapters 
    errEnable = objNetAdapter.EnableStatic(strIPAddress, strSubnetMask) 
    errGateways = objNetAdapter.SetGateways(strGateway, strGatewaymetric) 
    If errEnable = 0 Then 
        WScript.Echo "The IP address has been changed." 
    Else 
        WScript.Echo "The IP address could not be changed." 
    End If 

next

I found reading the variables before putting them into an array was the key



来源:https://stackoverflow.com/questions/37103582/change-default-gateway-using-vbscript-by-altering-last-octet-of-ip

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