I'm trying to enumerate all existing groups on my local machine.
That's what I tried using wmi :
string _class = "Win32_GroupUser";
string namespace = "\\\\.\\ROOT\\cimv2";
ManagementClass _class = new ManagementClass(namespace + ":" + class );
foreach (ManagementObject _object in _class.GetInstances())
{
richTextBox1.AppendText((_object["GroupComponent"].ToString()));
}
Output example :
\DESKTOP-2MSGC9J\root\cimv2:Win32_Group.Domain="DESKTOP-2MSGC9J",Name="Utilisateurs
du journal de performances"
In this output only the group name Name="Utilisateurs du journal de performances" is important to me.
Is a way to do a wmi query that only return that element in this _object ?
Another foreach with _object maybe.
I find a dirty way using substring after getting my object from wmi.
foreach (ManagementObject _object in _class.GetInstances())
{
string groups = _object["GroupComponent"].ToString();
int i = groups.LastIndexOf('=') + 1;
string groupsName = groups.Substring(i);
richTextBox1.AppendText(groupsName + "\r\n\r\n");
}
Related
I've been trying to retrieve information about remote computers in our network via a WMI query. This works fine for all the info I need, I just don't seem to get the UserFriendlyName from the WmiMonitorID class. As this value is stored as a uint16.
The code below returns System.UInt16[]
But I would like to get some readable information.
This is the method I use to retrieve the information:
GetDirectWmiQuery("UserFiendlyName", "WmiMonitorID");
public static string GetDirectWmiQuery(string item, string table)
{
string result = string.Empty;
ManagementScope scope;
scope = new ManagementScope($"\\\\{Var.hostnm}\\root\\WMI");
scope.Connect();
ObjectQuery query = new ObjectQuery($"Select {item} FROM {table}");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
result += m[item].ToString();
}
return result;
}
Translated to C# based on the excellent answer from Jimi,
The returned array needs to be converted to a string, to become human-eye-friendly. The UInt16 byte array can be converted with Convert.ToByte(UInt16), then tranformed into string with Encoding.GetString().
foreach (ManagementObject m in queryCollection)
{
var data = (ushort[])m[item];
var monitorID = Encoding.UTF8.GetString((data).Select(Convert.ToByte).ToArray());
result+= monitorID + "\n";
}
I need to get the Parent property of network adapter device from c# program
Please find the image here
Tried below code but the property "Parent" is not available
List mappingIpDeviceIds = new List();
Console.WriteLine("Reading Id and IP address...");
ManagementObjectSearcher adapters = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionStatus = 2");
foreach (ManagementObject item in adapters.Get())
{
foreach (ManagementObject setting in item.GetRelated("Win32_NetworkAdapterConfiguration"))
{
var relationships = setting.GetRelationships();
var name = setting["Caption"].ToString();
string[] defaultIPGateway = (string[])setting.GetPropertyValue("DefaultIPGateway");
string[] compterips = (string[])setting.GetPropertyValue("IPAddress");
string dhcpserver = (string)setting.GetPropertyValue("DHCPServer");
foreach (ManagementObject win32PnPEntity in item.GetRelated("Win32_PnPEntity"))
{
var x = win32PnPEntity.Properties;
foreach (var prop in x)
{
Console.WriteLine("::: PROPERTY NAME ::: " + prop.Name);
Console.WriteLine("::: PROPERTY VALUE ::: " + prop.Value);
}
}
MappingIpDeviceId mappingIpDeviceId = new MappingIpDeviceId();
string deviceid = (string)item.GetPropertyValue("PNPDeviceID");
string deviceid1 = (string)item.GetPropertyValue("ProductName");
string[] devicenames = deviceid.Split(new Char[] { '\\' });
foreach (string dn in devicenames)
{
mappingIpDeviceId.OWLIP = dhcpserver;
mappingIpDeviceId.ComputerIP = compterips[0];
mappingIpDeviceId.DeviceId = dn;
mappingIpDeviceIds.Add(mappingIpDeviceId);
}
}
}
There are two ways you can refer to:
Using PowerShell command Get-PnpDeviceProperty: Get-PnpDeviceProperty -KeyName 'DEVPKEY_Device_Parent' -InstanceId 'xxxxxxxxxxxxxxxx'
Use CM_Get_Parent. "Determining the Parent of a Device".
I need to get the power settings for a machine using WMI. I am using the MSDN Link to get the required values. I need specific values from the list returned. The following C# code does this:
string NamespacePath = #"root\cimv2\power";
string powerPlanClass = "Win32_powerplan";
string powerSettingClass = "Win32_PowerSettingDataIndex";
ManagementClass powerPlanManagementClass = new ManagementClass(NamespacePath + ":" + powerPlanClass);
ManagementObject powerPlanManagementObject = null;
foreach (ManagementObject managementObject in powerPlanManagementClass.GetInstances())
{
if (managementObject["IsActive"] != null && Boolean.Parse(managementObject["IsActive"].ToString()))
{
powerPlanManagementObject = managementObject;
}
}
Dictionary<string, PowerSetting> powerItems = new Dictionary<string, PowerSetting>()
{
{"AC", new PowerSetting() },
{"DC", new PowerSetting() }
};
foreach (ManagementObject oObject in powerPlanManagementObject.GetRelated(powerSettingClass))
{
var instanceId = oObject["instanceId"];
string[] powerSourceSettings = instanceId.ToString().Split(new string[] { #"\" }, StringSplitOptions.RemoveEmptyEntries);
var powerSourceType = powerSourceSettings[2];
ManagementObjectCollection managementObjects = oObject.GetRelated("Win32_PowerSetting");
var elementName = string.Empty;
foreach (var managementObject in managementObjects)
{
elementName = managementObject["ElementName"].ToString();
}
var indexValue = uint.Parse(oObject["settingindexvalue"].ToString());
if (elementName.Equals("Hibernate after",StringComparison.OrdinalIgnoreCase))
{
if (powerSourceType.Equals("AC", StringComparison.Ordinal))
{
powerItems["AC"].HibernateAfter = indexValue;
}
}
}
Note the match to the string "Hibernate after". This works on a machine with locale en-us but does not work with a different locale. Is there any other way to get the WMI property independent of the machine's locale?
Probably you can use GUID in the InstanceID of Win32_PowerSetting class instead of ElementName. In my machine, it is Microsoft:PowerSetting\{9d7815a6-7ee4-497e-8888-515a05f02364}. Although I couldn't find official document, this GUID, 9d7815a6-7ee4-497e-8888-515a05f02364 seems to be common for some Windows versions and locales as the identifier for "hibernate after" or "hibernate idle".
OK, so this drives me nuts.
The code below worked just fine in Windows 7 with .NET 3.5.
In Windows 8.1 and .NET 4.5.1 I get an empty result, but using the WMI Code Creator I can get the results.
I cannot find anything about this online.
I want to get the friendly names of any COM ports, e.g. "Communications Port (COM1)".
Just using System.IO.Ports.SerialPort.GetPortNames() wont do.
I really hope someone know how to do this. Thanks!
using System;
using System.Collections.Generic;
using System.Management;
namespace OakHub
{
public class SerialMgmt
{
static public List<String> GetCOMDevices()
{
List<String> list = new List<String>();
ManagementScope scope = new ManagementScope(#"\\" + Environment.MachineName + #"\root\CIMV2");
SelectQuery sq = new SelectQuery("SELECT Caption FROM Win32_PnPEntity");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, sq);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
String name = mo.ToString();
if (name.ToString().Contains("(COM"))
{
list.Add(name);
}
}
return list;
}
}
}
First of all I dont know why this code is even working for you (with .Net 3.5).
You just selected the property Caption. (Use * to select all, if needed)
I think you want the name of the Win32_PnPEntity-Devices, you cant get it with this line of code
String name = mo.ToString();
Because the Name is a property. You First have to load the Property with the WMI-String :
SELECT Name,Caption FROM Win32_PnPEntity //Get Name and Caption Property
or
SELECT * FROM Win32_PnPEntity //Load all the Propertys of that WMI-Obj
And than you have to check if value is null else --> return the value
Code:
public List<String> GetLocalCOMDevices()
{
List<String> list = new List<String>();
ManagementScope scope = new ManagementScope(#"\\" + Environment.MachineName + #"\root\CIMV2");
SelectQuery sq = new SelectQuery("SELECT Name,Caption FROM Win32_PnPEntity");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, sq);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
object propName = mo.Properties["Name"].Value;
if (propName == null) { continue; }
list.Add(propName.ToString());
}
return list;
}
I have checked the two other threads and even used code from one but it never populates a list. When I open up Active Directory Users and Computers and go to my Manager under Organization I see his list of direct reports.
What I am trying to do is gain access to that list through code. Nothing I have found so far seems to work.
public void GetDirectoryEntry(string adUserName)
{
DirectoryEntry de = new DirectoryEntry("LDAP://server.server.com");
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + adUserName + "))";
ds.SearchScope = SearchScope.Subtree;
SearchResult rs = ds.FindOne();
string distinguishedName = rs.Properties["distinguishedName"][0].ToString();
string department = rs.Properties["department"][0].ToString();
string manager = rs.Properties["manager"][0].ToString();
//string temp3 = rs.Properties["Reports"][0].ToString();
}
I have tried using Reports and directReports and neither work both error out.
This method loads up the logged in user or any user I pass into it. I can access all of their properties but I cannot seem to get access to their direct reports.
What am I missing?
Found the answer:
foreach (string objProperty in rs.Properties["DirectReports"])
{
isManager = true;
string emp = objProperty.ToString();
string[] setp = new string[1];
setp[0] = "DC"; //If your users are in a OU use OU
emp = emp.Split(setp, StringSplitOptions.None)[0];
emp = emp.Replace("CN=", "");
emp = emp.TrimEnd(',');
emp = emp.Replace("\\, ", ", ");
emp = emp.Split(',')[0];
//emps.Add(emp);
}
foreach (string objProperty in rs.Properties["DirectReports"])
{
isManager = true;
string emp = objProperty.ToString();
string[] setp = new string[1];
setp[0] = "DC"; //If your users are in a OU use OU
emp = emp.Split(setp, StringSplitOptions.None)[0];
emp = emp.Replace("CN=", "");
emp = emp.TrimEnd(',');
emp = emp.Replace("\\, ", ", ");
emp = emp.Split(',')[0];
//emps.Add(emp);
}