I have a problem with getting MSFT_NetConnectionProfile. I am able to access MSFT_NetAdapter and Win32_NetworkAdapter but I need informations from profile.
When I try to get it via PowerShell then there is no problem. Using a command found here on SO.
Get-WmiObject -Namespace root/StandardCimv2 -Class MSFT_NetConnectionProfile | Format-Table InterfaceAlias, Name
WBEMTest loads everything without error. I found WBEMTest here on SO
My C# code is:
using System.Management;
ManagementScope scope = new ManagementScope("ROOT\\StandardCimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM MSFT_NetConnectionProfile");
ManagementObjectSearcher networkAdapterSearcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection objectCollection = networkAdapterSearcher.Get();
try
{
foreach (ManagementObject item in objectCollection)
{
Console.WriteLine(item["Name"]);
Console.WriteLine(item["InterfaceAlias"]);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
I found that it works on my main development PC, but I need it to run on our embedded PC. The code sample is builded with .NET6 as single file application with .NET included (not installed on destination PC) so I suppose all DLLs should be linked.
Where should I look for the problem?
Related
I'm having trouble connecting to remote computer to grab a list of processes running.
For my test machine I'm using the username #"ownme\veritas". The password is just "veritas".
The sample domain is "ownme".
return new System.Management.ConnectionOptions()
{
//certainly these variables have been checked and are correct
Username = UserCredential.DomainUser,
Password = UserCredential.Password
};
This is where I'm trying to do the connection. I don't know, but this might actually be the issue here. It could also be I didn't fill out enough fields in the ConnectionOptions above.
I referred to these two articles:
https://www.experts-exchange.com/questions/23514935/How-to-use-GetProcess-for-remote-sytems.html
https://msdn.microsoft.com/en-us/library/system.management.connectionoptions.authentication.aspx
I can't figure out what I'm doing wrong
ManagementScope scope = new ManagementScope($"\\\\{computer.DnsHostname}\\root\\cimv2", connectionOptions);
scope.Connect();
//Error: Access is denied
var processes = System.Diagnostics.Process.GetProcesses(dnsHostName);
GetProcesses will use the current users credentials to connect to the remote machine, not the credentials you specified via ConnectionOptions.
You need to use the WMI scope object that you created with the correct credentials to issue a query for the processes like this:
//..
SelectQuery query = new SelectQuery("select * from Win32_Process"); //query processes
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
using (ManagementObjectCollection collection = searcher.Get())
{
foreach (var process in collection) //loop through results
{
var name = process["name"]; //process name
//Do something with process
}
}
}
I didn't realize this was such a highly viewed question: I found the answer a long time ago. I actually didn't use WMI to do it. We actually filed a ticket with Microsoft and the discounted us for free after they gave us the answer. The answer is:
LogonUser + NEW_CREDENTIALS
workWhen i try show list with adapters name in combobox like this:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\StandardCimv2","SELECT * FROM MSFT_NetAdapter");
foreach (ManagementObject queryObj in searcher.Get())
{
try
{
comboBox1.Items.Add(queryObj["Name"].ToString());
}
catch (Exception)
{
comboBox1.Items.Add("");
}
}
All good...because used Windows 8. If i run app on PC with Windows 7 i get error:
System.Management.ManagementException: Invalid namespace
Later I noticed one thing...if this line code:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\StandardCimv2","SELECT * FROM MSFT_NetAdapter")
Replace on this:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapter");
The error disappears and everything works. And now Question!
Why this "root\StandardCimv2" not work in Win7? But with this "root\CIMV2" all good.
Thanks in advance.
The Win32_NetworkAdapter class works on Vista and 7.
This answer has an example of using it (in PowerShell) to retrieve Name and connection Speed:
https://stackoverflow.com/a/3002568/550712
It looks like it also has the "Name" property so it might work as a direct replacement in your code.
I am trying to figure out if the Active Directory Domain Services are installed a windows server.
I know they show up in the Server Manager, but can I programmatically get if the role is installed on a server using C# code
If you know the name of the server you want to test and can run the program with domain admin privileges remotely, you can use WMI:
internal static bool IsDomainController(string ServerName)
{
StringBuilder Results = new StringBuilder();
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("\\\\" + ServerName + "\\root\\CIMV2",
"SELECT * FROM Win32_ServerFeature WHERE ID = 10");
foreach (ManagementObject queryObj in searcher.Get())
{
Results.AppendLine(queryObj.GetPropertyValue("ID").ToString());
}
}
catch (ManagementException)
{
//handle exception
}
if (Results.Length > 0)
return true;
else
return false;
}
If you're running that locally on the server, the WMI path changes to:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_ServerFeature WHERE ID = 10");
See the MSDN reference on Win32_ServerFeature for a full list of roles and their ID numbers.
If your question is to see if a server is a domain controller, you can enumerate the domain controllers in the domain and check the hostname of the server you are sitting on to see if it matches any of them. To get the list of domain controllers:
var domainControllers = new List<string>();
var domain = Domain.GetCurrentDomain();
foreach (var dc in domain.DomainControllers)
{
domainControllers.Add(dc.Name);
}
string whoami = Dns.GetHostname();
Make sure to add requisite error handling (like if you run this on a workgroup computer, it will die).
EDIT:
Alternate ways of detecting DCPROMO (because it's possible to install Domain Services without DCPROMO, and that is a bad thing):
1) Parse out (and check for the existence of) the debug log that is created when DCPROMO does its thing. Should be located at c:\windows\debug\dcpromo.log
2) This DSQUERY command is FAST and will give you all the servers where DCPROMO was ran:
dsquery * "cn=Sites,cn=Configuration,dc=MyDomain,dc=com" -Filter "(cn=NTDS Settings)" -attr distinguishedName whenCreated
Problem is getting that from command line output if you started it using Process. Working on a way to do this and will update once I have it tested, as I haven't done AD filtering in a query for a while.
I am trying to get Server Network Protocol (SQL Server) using WMI.
I had written small application:
---------------------------C# code--------------------------
ManagementScope scope = new ManagementScope(#"\\computerName\root\Microsoft\SqlServer\ComputerManagement");
scope.Options.Username = "Administrator";
scope.Options.Password = "Password";
scope.Connect();
var query = new ObjectQuery(#"SELECT * FROM ServerNetworkProtocol");
var searcher = new ManagementObjectSearcher(scope, query);
var managementObjectCollection = searcher.Get();
var result = managementObjectCollection.Cast<ManagementObject>().ToList(); //<---- FileNotFoundException
var s = result.First()["ProtocolName"].ToString();
MessageBox.Show(String.Format("Protocol name: {0}", s));
And when I run the application, I will receive System.IO.FileNotFoundException.
I tested the query using WBEMTest Utility and everything is okey (with Administrator credentials).
Later I had written test service and put the same code, and service works correctly without any exceptions.
I suppose the problem related with credentials.
Can anyone explain more detailed what's wrong. What permissions need to run this query (if problem with credentials) and how I can resolve the issue.
I will be appreciated for any help.
just check credential and change one line :
ManagementScope scope = new ManagementScope(#"\\computerName\root\Microsoft\SqlServer\ComputerManagement10");
I'm using C# to call GetVolumeInformation on a remote machine. I can hit the remote harddrives easily as there is a default share setup of c$ or whatever. However, CD/DVD do not have a default setup. How can I read the remote CD/DVD drive using a PInvoke call or something else?
If I can't do it using C#, I could always use PowerShell or WMI.
The WMI allows you to get system information of a remote machine without problems, only you need set the remote WMI access in the machine and use a valid user and password. on this case you can use the Win32_LogicalDisk and Win32_CDROMDrive classes to retrieve the info which you need.
Try this C# sample.
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
static void Main(string[] args)
{
try
{
string ComputerName = "localhost";//set the remote machine name here
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";//user
Conn.Password = "";//password
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_CDROMDrive");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
Console.WriteLine("{0,-35} {1,-40}","DeviceID",WmiObject["DeviceID"]);// String
Console.WriteLine("{0,-35} {1,-40}","Drive",WmiObject["Drive"]);// String
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}
Using Powershell and WMI.
Try this:
Get-WmiObject -computername MyremotePC Win32_CDROMDrive | Format-List *
You need administrative credential on remote computer.
You can P/invoke in powershell the GetVolumeInfomation adding it as type using Add-Type (Some example here).
If you're trying to read data on the disk of a remote CD/DVD that isn't shared I don't know any way to do it.