简体   繁体   中英

Resolving the WMI DNS Host Name

I am trying to make a comparison between a machine name i have retrieved from AD, and the DNS Host Name i want to get using WMI from the machine.

I currently have:

foreach (SearchResult oneMachine in allMachinesCollected)
            {
                pcName = oneMachine.Properties["name"][0].ToString();
                ConnectionOptions setupConnection = new ConnectionOptions();
                setupConnection.Username = USERNAME;
                setupConnection.Password = PASSWORD;
                setupConnection.Authority = "ntlmdomain:DOMAIN";
                ManagementScope setupScope = new ManagementScope("\\\\" + pcName + "\\root\\cimv2", setupConnection);
                setupScope.Connect();

                ObjectQuery dnsNameQuery = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
                ManagementObjectSearcher dnsNameSearch = new ManagementObjectSearcher(setupScope, dnsNameQuery);
                ManagementObjectCollection allDNSNames = dnsNameSearch.Get();
                string dnsHostName;
                foreach (ManagementObject oneName in allDNSNames)
                {
                    dnsHostName = oneName.Properties["DNSHostName"].ToString();
                    if (dnsHostName == pcName)
                    {
                        shutdownMethods.ShutdownMachine(pcName, USERNAME, PASSWORD);
                        MessageBox.Show(pcName + " has been sent the reboot command");
                    }
                }
            }
        }

But i get a ManagementException >> dnsHostName = oneName.Properties["DNSHostName"].ToString(); << here saying not found. Any ideas?

Depending on the operating system you are connecting to this property will not be available. You can see from the documentation that it is not available on Windows 2000 and XP. However, it is available on the Win32_NetworkAdapterConfiguration class, but you will receive more than one object, which you will have to loop over to get the name as most of them will be null.

Also, dnsHostName = oneName.Properties["DNSHostName"].ToString(); is not correct. It should be dnsHostName = oneName.Properties["DNSHostName"].Value.ToString() . Again, if you decide to use Win32_NetworkAdapterConfiguration keep in mind that it can be null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM