I’m a beginner in programming. I wrote a script to set DNS setting using VB. I was able to set the primary address.
However, I don’t know how to set the secondary address because it will require the use of array.
How can this be done?
Dim DNS As String() = {"192.168.1.1", "192.168.1.2"}
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If (Not CBool(objMO("IPEnabled"))) Then
Continue For
End If
Try
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewDNS As ManagementBaseObject = Nothing
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")
'Set DNS to DHCP
objNewDNS("DNSServerSearchOrder") = New String() {DNS()}
objSetIP = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDNS, Nothing)
Console.WriteLine("Updated IPAddress, SubnetMask and Default Gateway!")
Catch ex As Exception
MessageBox.Show("Unable to Set IP : " & ex.Message)
End Try
Next objMO
In VB.Net the
Dimkeyword is actually short for Dimension and can be used for declaring arrays.Simply apply brackets to the variable or type and hey presto you have an array.
Or
Of course, its a little more complicated than that. You may want to declare your array with a predefined number of elements, say 5, assuming
Option Base 0.Or you might want to assign your array with a number of predefined values.
You can also use this syntax,
for instance. Your example,
seems perfectly valid.
In your example you have the misforstune to be using WMI. I see you want to invoke the
"SetDNSServerSearchOrder"method on the"Win32_NetworkAdapterConfiguration"class.The
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")sets objNewDNS to aManagementBaseObjectthat is a collection of parameters for the"SetDNSServerSearchOrder"method.The
"SetDNSServerSearchOrder"takes one parameter called"DNSServerSearchOrder"as described here which happens to be an array of strings.So unless I’m mistaken, and assuming the string array
DNSis your search order, your code should read:note that this code discards the return value of the method call.
EDIT:
From your comments it seems that the object returned by the
objMO.InvokeMehtodcall is actually aManagementBaseObject. This wraps the “returnValue” of the invoked method. So somthing like the code below will help you get to the return value, if necessary.So your problems are not related to your ability to declare arrays but rather the tedious interface to WMI. I guess you might need a few more calls for your console output to be entirely valid but I hope this helps you out.