Change IP Address in VB.Net - vb.net

I am writing a Windows Forms App in VB.Net that will (among other things) change the IP Address, Default Gateway, Subnet Mask, and set the IP Address to Static on an image of Winfows 7 only. Sysprep is not being used. I have searched Google and only come up with 2 options. I don't believe the first solution will work for me because I do not necessarily know the name of the connection. It uses netsh to change IP settings. I was going to give a link to this example but I can't post more than 2 links...
The second solution is shown at this link (the VB.Net version) and the original code is here (the C# version). This solution uses WMI which I really don't know that much about.
When I debug the code and look at everything the code seems to be executing properly but the IP Address is still set to DHCP and all of the other setting are still the same. So, basically, what gives? Why does this code seem to not work?
Here is my code. I only made a few changes:
'Changed the 3 IPs below
Dim IPAddress As String = "192.168.1.105"
Dim SubnetMask As String = "255.255.252.0"
Dim Gateway As String = "192.168.1.100"
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 objNewGate As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableStatic")
objNewGate = objMO.GetMethodParameters("SetGateways")
'Set DefaultGateway
objNewGate("DefaultIPGateway") = New String() {Gateway}
objNewGate("GatewayCostMetric") = New Integer() {1}
'Set IPAddress and Subnet Mask
objNewIP("IPAddress") = New String() {IPAddress}
objNewIP("SubnetMask") = New String() {SubnetMask}
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)
'Changed this line so I could see if it was executing all of the way
MessageBox.Show("Updated IPAddress, SubnetMask and Default Gateway!")
Catch ex As Exception
MessageBox.Show("Unable to Set IP : " & ex.Message)
End Try
Next objMO

I can answer my own question. I thought of it in the shower (how cliche right?). Because this is Windows 7, all I needed to was right-click and run the program as an administrator.

Related

In vb.net how do you read non-hidden devices as seen in device manager Network Adaptor section

I am trying to read the network adapters
as seen here
at the moment I am using the code I found online
Sub Main()
Dim path As ManagementPath = New ManagementPath()
path.Server = "."
path.NamespacePath = "root\CIMV2"
Dim scope As ManagementScope = New ManagementScope(path)
Dim query As ObjectQuery = New ObjectQuery("SELECT * FROM Win32_NetworkAdapter")
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(scope, query)
Dim queryCollection As ManagementObjectCollection = searcher.Get()
Dim m As ManagementObject
For Each m In queryCollection
Console.WriteLine("Device Name : {0}", m("Name"))
Next
Console.ReadLine()
End Sub
Right now I am seeing a list of devices that include those 4, but also a bunch of hidden devices and what looks like devices that are not connected anymore. How do I refine my search to only show what the device manager shows by default?
Found my answer on another forum, but cannot find the link again. Here is the answer:
Dim moIP As ManagementObject
Dim myNet = New ManagementObjectSearcher _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
Dim CountIncrement As Int16 = 1
For Each moIP In myNet.Get
Console.WriteLine()
'find device with MAC Address
If CStr(moIP("MACAddress")) = "00:11:22:33:44:55" Then
'code here
End If
Next
Edit: inside the for loop, these checks can also be done for finding information about connected devices.
Console.WriteLine("Device Name : {0}", moIP("Caption"))
Console.WriteLine("Service Name : {0}", moIP("ServiceName"))
Console.WriteLine("Description Name : {0}", moIP("Description"))
Console.WriteLine("MAC : {0}", moIP("MACAddress"))
Console.WriteLine(moIP("IPAddress")(0))

Namespace Crossroads

I'm a novice coder so I'm not that knowledgeable. Please be kind with my silly questions.
I am writing an IP address switching utility
I've got two VB.NET functions:
GetNIC() and MakeStatic()
GetNIC() uses the System.Net.NetworkInformation namespace. I have it running to find the current IPv4 adapter, IP, DGW, SM and other info.
MakeStatic() uses the System.Management namespace. I am trying to figure out how to use the info from GetNIC() to single out the same adapter and change the info. Here is a snippet of my code to switch the IP. I never really have used ManagementBaseObjects before and was wondering how to find the GUID (or something) that matches the GUID I have already found in GetNIC().
Dim objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewGate As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableStatic")
objNewGate = objMO.GetMethodParameters("SetGateways")
'Set DefaultGateway
objNewGate("DefaultIPGateway") = New String() {Gateway}
objNewGate("GatewayCostMetric") = New Integer() {1}
'Set IPAddress and Subnet Mask
objNewIP("IPAddress") = New String() {IPAddress}
objNewIP("SubnetMask") = New String() {SubnetMask}
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)
Basically I'm shooting for:
If objMO.<<something>> = NICguid then
<<<Do the above code>>
End IF
FOUND IT!
objMO("MACAddress")
Thanks!

VB NET Read Remote Registry

I'm trying to get the architecture and the operating system of many remote pcs.
In order to do that i'm querying Win32_OperatingSystem and parsing the "Caption" for the O.S. and for the architecture im reading OSArchitecture .
In Windows XP this value does not exists, so i thought that reading the HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE
would have done the trick like this code:
Try
Dim co As New ConnectionOptions
co.Impersonation = ImpersonationLevel.Impersonate
co.Authentication = AuthenticationLevel.PacketPrivacy
co.EnablePrivileges = True
co.Username = username
co.Password = password
Dim scope As New ManagementScope("\\" & machine.Text & "\root\cimv2", co)
scope.Connect()
Dim environmentKey, asd2 As Microsoft.Win32.RegistryKey
Dim asd As String
environmentKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine.Text)
asd2 = environmentKey.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", True)
asd = asd2.GetValue("PROCESSOR_ARCHITECTURE")
Debug.Print("asd: " + asd)
environmentKey.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
My problem is: if im trying this code I get an System.Security.SecurityException: "Accessing remote registry not permitted"
I am, and i know the administrator username and password.
In fact if I run a simple cmdkey /add:targetname /user:username /pass:password
It works.
So why do I have to run a cmdkey /add even if i have alredy specified the username and password in the ConnectionOptions ??
P.S. Sorry for my bad English
This may very well be because remote registry access is not enabled on the target PC.
Even if you know the administrator credentials, remote access to the registry will not work if the feature isn't enabled on the target PC.
To enable it, see the following Microsoft Knowledge Base Article, which covers a variety of Windows Operating Systems: https://support.microsoft.com/en-us/kb/314837
All right, i got it:
Const HKEY_current_user As String = "80000002"
Dim options As New ConnectionOptions
options.Impersonation = ImpersonationLevel.Impersonate
options.EnablePrivileges = True
options.Username = ".\administrator"
options.Password = "my_password"
Dim myScope As New ManagementScope("\\" & RemotePCHostname & "\root\default", options)
Dim mypath As New ManagementPath("StdRegProv")
Dim mc As New ManagementClass(myScope, mypath, Nothing)
Dim inParams As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParams("hDefKey") = UInt32.Parse(HKEY_current_user,System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParams("sSubKeyName") = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
inParams("sValueName") = "PROCESSOR_ARCHITECTURE"
Dim outParams As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParams, Nothing)
If (outParams("ReturnValue").ToString() = "0") Then
MessageBox.Show(outParams("sValue").ToString())
Else
MessageBox.Show("Error retrieving value : " + outParams("ReturnValue").ToString())
End If

Searching AD for a printer using VB.net

I am using VB.net, trying to query Active Directory to check and see if a printer exists there. I have an AD connection but it doesn't seem to return any values when I run the code. Here is the snippet of my code
Dim searchResults As New ArrayList
Dim myDirectorySearcher As New DirectorySearcher(myDirectoryEntry))
Dim targetObject as string = "printerName"
Dim searchFilter as string = "cn"
Dim strFilter = "(&(objectClass=printer)(" & searchFilter & "=" & targetObject & "))"
myDirectorySearcher.Filter = strFilter
myDirectorySearcher.CacheResults = False
For i = 0 To searchCriteria.Count - 1
myDirectorySearcher.PropertiesToLoad.Add(searchCriteria(i).ToString)
Next
Dim mySearchResult As SearchResult = myDirectorySearcher.FindOne()
Tried various methods but nothing seems to be working, any advice would be much appreciated.
I had to do something similar to this with a project I was working on at work. In short, I think you might be searching under the wrong objectClass in ActiveDirectory.
Printers sometimes get added under printQueue.
Your code would then be something like:
Dim searchResults As New ArrayList
Dim myDirectorySearcher As New DirectorySearcher(myDirectoryEntry))
Dim targetObject as string = "printerName"
Dim strFilter = "(&(objectClass=printQueue)(cn=" & targetObject & "))"
myDirectorySearcher.Filter = strFilter
myDirectorySearcher.CacheResults = False
For i = 0 To searchCriteria.Count - 1
myDirectorySearcher.PropertiesToLoad.Add(searchCriteria(i).ToString)
Next
Dim mySearchResult As SearchResult = myDirectorySearcher.FindOne()
It is also worth bearing in mind that sometimes the printerName will have the domain appended to the end, so your query may not always return the results you would expect.
For example your printer name may be PRINTER-RECEPTION but is referenced on your domain with PRINTER-RECEPTION.MYCOMPANY.DOMAIN.
Hope this helps you.

Best way to query disk space on remote server

I am trying to nail down free space on a remote server by querying all the drives and then looping until I find the drive I am seeking.
Is there a better way to do this?
Dim oConn As New ConnectionOptions
Dim sNameSpace As String = "\\mnb-content2\root\cimv2"
Dim oMS As New ManagementScope(sNameSpace, oConn)
Dim oQuery As System.Management.ObjectQuery = New System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3")
Dim oSearcher As ManagementObjectSearcher = New ManagementObjectSearcher(oMS, oQuery)
Dim oReturnCollection As ManagementObjectCollection = oSearcher.Get()
Dim oReturn As ManagementObject
For Each oReturn In oReturnCollection
'Disk name
Console.WriteLine("Name : " + oReturn("Name").ToString())
'Free Space in bytes
Dim sFreespace As String = oReturn("FreeSpace").ToString()
If Left(oReturn("Name").ToString(), 1) = "Y" Then
Console.WriteLine(sFreespace)
End If
Next
Why not just make your WMI query only pull back where name='Y'?
So:
Dim oQuery As System.Management.ObjectQuery = New System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3 AND name='Y'")