How to find Scope for ManagementScope? - c#

Anyone know how to find Scope ?
Microsoft say
ManagementScope scope = new ManagementScope("\\\\FullComputerName\\root\\cimv2");
I work in localhost.
I already test "\\HOSTNAME\root\cimv2" and "\\HOSTNAME\MY_ACCOUNT_NAME\cimv2" but they doesn't work.
I'm on Windows 7 Pro, I use Visual Studio 2010 and it's .NET 4
#
Update 1
int i = Convert.ToInt32(processIds[index]);
String queryString = "select CreationDate from Win32_Process where ProcessId='" + processIds[index] + "'";
SelectQuery query = new SelectQuery(queryString);
ManagementScope scope = new System.Management.ManagementScope("\\\\XXX-PC\\YYY\\cimv2");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection processes = searcher.Get();
#keyboardP : Searcher.Get() work an exception, so I suppose my Scope it's not right.

I've been developing an application that uses Management Scopes for quite some time now. I think you just have to omit the Host Name.
This works for me:
ManagementScope scope = new ManagementScope("\\root\\cimv2");
scope.Connect();

Related

Can't access hardware info of remote computer with WMI: Access is denied

I am trying to create an application that uses WMI to retrieve information about a computer on my local network. When I run it, I get an access denied error. Here is the code:
private void GetHDDdetails()
{
ConnectionOptions options = new ConnectionOptions();
options.Username = "username";
options.Password = "password";
options.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope oMs = new ManagementScope("\\\\remoteHostName\\root\\cimv2", options);
ObjectQuery oQuery = new ObjectQuery("SELECT Size FROM Win32_DiskDrive");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
ManagementObjectCollection oCollection = oSearcher.Get();
foreach (ManagementObject obj in oCollection)
{
hddBox.Text = obj["Size"].ToString();
}
}
I have replaced some of the info above, such as user name and password, with placeholders for this post.
Some of the things I have tried is this: Disabling firewall on both machines, making sure TCP NetBIOS service and RCP and WMI services are running on both. The account I am using is an administrator on the local computer. Everything I have found online tells me to check these, but it is obviously something else.
If someone can point me in the right direction, that would be great.
Please check using wbemtest that you can access the information from remote machine. And i hope you are replacing remoteHostName properly.
And make changes to authentication level, if you can.
scope.Options.EnablePrivileges = true;
scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;

WMI C# Server accepts RDP connections

We have 6 Citrix Servers. I'm trying to find out if Remote Logons are enabled/disabled.
I plan to put this onto of a webpage to display and green icon if they are or red if they aren't.
I've managed to connect to the machines and pull operating system information etc.. However when i try and connect to view the TerminalServiceSetting information.. i get an Invalid Class error.
Here is my code.
ManagementScope scope = new ManagementScope("\\\\MACHINENAME\\ROOT\\cimv2");
scope.Connect();
//create object query
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_TerminalServiceSetting");
//create object searcher
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
//get collection of WMI objects
ManagementObjectCollection queryCollection = searcher.Get();
//enumerate the collection.
foreach (ManagementObject m in queryCollection)
{
// access properties of the WMI object
Label1.Text = m["AllowTSConnections"].ToString();
}
If anyone can shed some light on it that would be great.
Thanks
Update:
I have now found the code (i think) that checks to see if remote connections are enabled or disabled.
ManagementScope scope =
new ManagementScope("\\\\MACHINENAME\\root\\CIMV2\\TerminalServices",con);
scope.Options.EnablePrivileges = true;
scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
scope.Options.Impersonation = ImpersonationLevel.Impersonate;
scope.Connect();
//create object query
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_TerminalServiceSetting");
//create object searcher
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
//get collection of WMI objects
ManagementObjectCollection queryCollection = searcher.Get();
//enumerate the collection.
foreach (ManagementObject m in queryCollection)
{
if (m["AllowTSConnections"].ToString() == "1")
{
Redicon.Visible = false;
}
else
{
Greenicon.Visible = false;
}
}
However when i run the code i get returned "1".. which is fine. However if i deny remote logins on the server and re run the code it stays at 1..
Any ideas?
You need to be sure that the server provide the TerminalServiceSetting information. WMI uses unmanaged code because not all servers and their configurations provide all information.
You can use Mgmtclassgen to generate managed code and at the same time make sure that the server provides the information.
Sorted!!!
I was looking up the wrong field.
the correct one is :
Label1.Text = "Remote Connections: " + m["Logons"].ToString();

wmi c#. copy file from remote machine

I use mgmtclassgen.exe and get wrapper(DataFile.cs) class for CIM_DataFile wmi class. Code below works perfect on localhost (without filling credentionals), but when I connect to remote machine variable returnResult=9 (Invalid object). But size of variable dataFileCollection=1
var _connectionOptions = new ConnectionOptions();
_connectionOptions.Username = "username";
_connectionOptions.Password = "password";
_connectionOptions.Authority = String.Format("ntlmdomain:{0}", "DOMAIN");
var _managementScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2",
"RemotePCName"), _connectionOptions);
var dataFileCollection = DataFile.GetInstances(_managementScope,
#"Name = 'C:\\Windows\\System32\\mapisvc.inf'";
var tempFilePath = "c:\\temp.txt");
if (dataFileCollection.Count > 0)
{
foreach (var dataFile in dataFileCollection.Cast<DataFile>())
{
var returnResult = dataFile.Copy(tempFilePath);
if (File.Exists(tempFilePath))
{
List<string> lines = File.ReadAllLines(tempFilePath).ToList();
File.Delete(tempFilePath);
}
}
}
try adjusting your management scope differently
Maybe you could try it like:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(
"\\\\" + strComputer + "\\root\\CIMV2",
"SELECT * FROM Win32_PerfFormattedData_MSSQLSERVER_SQLServerDatabases");
where strComputer is the name of the remote pc and Win32_Perf... the class you're trying to query. This works for me, as it is in a local network, though I am not certain where your remote machine is located.
You could as well to go http://www.microsoft.com/en-us/download/details.aspx?id=8572 which is a WMI-query generator by Microsoft. This allows you to generate query's in either C#, VB, and VB scripts. While setting the connection properties.
Might be worth a shot.

c# Active Directory via WMI

Does anyone has some example about accessing Active Directory, LDAP querying using WMI (System.Management namespace) and not System.DirectoryServices namespace.
Here on MSDN page it is described a little using CIM classes
http://msdn.microsoft.com/en-us/library/aa392320(v=VS.85).aspx
But I cant find some C# example realizing it.
For example, to access some Win32 class you have to initialize Scope object to use CIMV2 namespace
private ConnectionOptions connection;
private ManagementScope scope;
...
connection = new ConnectionOptions();
...
scope = new ManagementScope("\\\\" + computer + "\\root\\CIMV2", connection);
try
{
scope.Connect();
}
And use ObjectQuery class for querying WMI data
ObjectQuery objectQuery = new ObjectQuery("SELECT Name FROM Win32_Processor");
ManagementObjectSearcher searcher = ManagementObjectSearcher(scope, objectQuery);
foreach (ManagementObject queryObj in searcher.Get())
{
return queryObj["Name"].ToString();
}
How is it possible to access AD using the same scope?
Thanks :)

Problem retrieving Hostaddress from Win32_TCPIPPrinterPort

I'm running into an odd issue retrieving printer port addresses.
When I get all the entries in Win32_TCPIPPrinterPort, the HostAddress field (which should have the IP address) is usually blank/null, only the port name has a value. To make it a bit stranger, if a particular port is not in use by any printer, THEN the HostAddress will have the the proper value.
The C# code is simple, and results in something like this;
IP_192.168.1.100,
printerportxyz,
richTextBox1.Clear();
ManagementObjectSearcher portSearcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_TCPIPPrinterPort");
foreach (ManagementObject port in portSearcher.Get())
{
richTextBox1.AppendText(
String.Format("Name: {0} HostAddress: {1}",
port["Name"],
port["HostAddress"])
);
}
I also tried the same thing in WSH/VBS, and saw the same behavior.
I ended up having to re-visit this, and making another attempt. I found that the built-in prnport.vbs managment script had no issues - looking into it I saw that while establishing its WMI connection it had oService.Security_.Priveleges.AddAsString "SeLoadDriverPrivilege"
the solution in C# ended up specifying the WMI ConnectionOptions and setting EnablePrivileges to true. Then the HostAdress was no longer null for unused or in-use ports.
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.EnablePrivileges = true;
ManagementScope mgmtScope = new ManagementScope("root\\CIMV2", connOptions);
mgmtScope.Connect();
ObjectQuery objQuery = new ObjectQuery("SELECT * FROM Win32_TCPIPPrinterPort");
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(mgmtScope, objQuery);
foreach (ManagementObject mo in moSearcher.Get())
{
Console.WriteLine(String.Format("PortName={0} HostAddress={1}", mo["Name"], mo["HostAddress"]));
}

Categories