问题
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