我尝试通过vb.net程序与WMI进行交互,以使任何运行此程序的计算机从DHCP为所有具有IP的网络适配器提取IP设置和DNS服务器设置。
我目前为DHCP工作的代码没有问题,但不会更改DNS设置。程序编译并执行没有问题,但DNS设置不会更改为从DHCP自动获取。
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 objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewDNS As ManagementBaseObject = Nothing
Dim objSetDNS As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableDHCP")
objSetIP = objMO.InvokeMethod("EnableDHCP", Nothing, Nothing)
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")
objSetDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", Nothing, Nothing)
Catch ex As Exception
MessageBox.Show("Settings unchanged : " & ex.Message)
End Try
Next objMO
我非常接近解决这个问题,我只是需要帮助才能找到最后一步。
答案 0 :(得分:1)
你烦人地必须通过注册表来做,他们没有为它添加WMI方法。具体来说(取自这里:https://gallery.technet.microsoft.com/7b1cec46-bdb8-4afc-b240-9789eefce6de),您需要将此键设置为null。
"HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\"
以下是您的代码,其中插入了必要的新子
Const conKeyPath = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
Public Sub Test()
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 objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewDNS As ManagementBaseObject = Nothing
Dim objSetDNS As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableDHCP")
objSetIP = objMO.InvokeMethod("EnableDHCP", Nothing, Nothing)
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")
objSetDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", Nothing, Nothing)
SetDNSAutomatically(objMO.GetPropertyValue("settingID"))
Catch ex As Exception
MessageBox.Show("Settings unchanged : " & ex.Message)
End Try
Next objMO
End Sub
Private Sub SetDNSAutomatically(ByVal settingID As String)
If settingID = String.Empty Then
Throw New ArgumentNullException("settingID")
End If
Dim _adapterKeyPath = String.Format("{0}\{1}", conKeyPath, settingID)
My.Computer.Registry.SetValue(_adapterKeyPath, "NameServer", String.Empty)
End Sub