How to get a list users in Task Manager - c#

How to get a list users in Task Manager with status?
I found only how to get a list of domain users
var usersSearcher = new ManagementObjectSearcher(#"SELECT * FROM Win32_UserAccount");
var users = usersSearcher.Get();

You can try this code to get the list of users:
var usersSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_UserAccount");
var managementObjects = usersSearcher.Get();
List<string> result = new List<string>();
foreach (ManagementObject item in managementObjects)
{
foreach (var pr in item.Properties)
{
if (pr.Name == "Caption")
{
result.Add(pr.Value?.ToString());
}
}
}
var users = result.Distinct().ToList();
Also you may try this:
var usersSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process");
var managementObjects = usersSearcher.Get();
List<string> allUsers = new List<string>();
foreach (ManagementObject obj in managementObjects)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
allUsers.Add(argList[1] + "\\" + argList[0]);
}
}
var result = allUsers.Distinct().ToList();

Related

Get Parent property of network adapter device from c#

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".

View like Task manager with filter

I'm trying to make an app where I could see the process, path, user, and description like Task Manager Details, which I have made but I want a filter to search from the source code where the image path contains 'Chrome' for example or If you could help me to get the Description like the task manager image and filter with this column. If you can help me to get the username of the process without using the another method will be nice.
Thank you.
This is what i have improved.
DataTable dt = null;
private void Form1_Load(object sender, EventArgs e)
{
var wmiQueryString = "SELECT * FROM Win32_Process";
// var wmiQueryString = "SELECT * FROM Win32_ComputerSystem";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
{
var query = from p in Process.GetProcesses()
join mo in results.Cast<ManagementObject>()
on p.Id equals (int)(uint)mo["ProcessId"]
select new
{
Process = p.ProcessName,
Path = (string)mo["ExecutablePath"],
CommandLine = (string)mo["CommandLine"],
User = GetProcessOwner(p.Id),
Description = mo["Description"]
};
dt = ConvertToDataTable(query);
dataGridView1.DataSource = dt;
}
}
DataTable ConvertToDataTable<TSource>(IEnumerable<TSource> source)
{
var props = typeof(TSource).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(
props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray()
);
source.ToList().ForEach(
i => dt.Rows.Add(props.Select(p => p.GetValue(i, null)).ToArray())
);
Array a = source.ToArray();
for (int i = 0; i < a.Length; i++)
{
var x = a.GetValue(i);
//if (true)
//{
// DataRow r = dt.NewRow();
// r.
//}
a.ToString();
}
return dt;
}
public string GetProcessOwner(int processId)
{
string query = "Select * From Win32_Process Where ProcessID = " + processId; ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementObjectCollection processList = searcher.Get(); foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty }; int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); if (returnVal == 0)
{
// return DOMAIN\user
return argList[0];
}
}
return "NO OWNER";
}
What I have
TaskManager what I want
The process description comes from the file description. You can grab it like so:
private void Form1_Load(object sender, EventArgs e)
{
var wmiQueryString = "SELECT * FROM Win32_Process";
// var wmiQueryString = "SELECT * FROM Win32_ComputerSystem";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
{
var query = from p in Process.GetProcesses()
join mo in results.Cast<ManagementObject>()
on p.Id equals (int)(uint)mo["ProcessId"]
select new
{
Process = p.ProcessName,
Path = (string)mo["ExecutablePath"],
CommandLine = (string)mo["CommandLine"],
User = GetProcessOwner(p.Id),
Description = GetDescription((string)mo["ExecutablePath"])
};
dt = ConvertToDataTable(query);
dataGridView1.DataSource = dt;
}
}
string GetDescription(string executablePath)
{
if (!File.Exists(executablePath))
{
return "No Description";
}
return FileVersionInfo.GetVersionInfo(executablePath).FileDescription;
}
You'll probably need to run your program as an administrator to show the details of all processes.
Why would you like to get the username with another method?

How to search in a List by first item

Here is my list:
public static List<Tuple<string, string>> hardDiskInfo(string hostname)
{
var hardDiskInfo = new List<Tuple<string, string>>();
ManagementScope Scope;
if (!hostname.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = Properties.Settings.Default.uName;
Conn.Password = Properties.Settings.Default.pWord;
Conn.Authority = "ntlmdomain:" + Properties.Settings.Default.doMain;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", hostname), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", hostname), null);
Scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3 OR DriveType = 4");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(Scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject mo in queryCollection)
{
foreach (PropertyData p in mo.Properties)
{
if (p.Value != null)
{
hardDiskInfo.Add(new Tuple<string, string>(p.Name.ToString(), p.Value.ToString()));
}
}
}
return hardDiskInfo;
}
I'd like to know how to get the second p.Value of the p.Name after calling it:
hardDiskInfo(inputText.Text);
For example the value of the "FreeSpace" which is defined in Win32_LogicalDisk.
I'm having more Win32_ queries so knowing this will help me handling all of them and I'll be a happy panda.
Thank you.
Are the Names unique?
You might try:
var values = hardDiskInfo(inputText.Text);
// Get the first or default which matches "FreeSpace".
var freeSpaceInfo = values.FirstOrDefault(item => item.Item1 == "FreeSpace");
// If it was found,
if(freeSpaceInfo != null)
{
MessageBox.Show($"FreeSpace: {freeSpaceInfo.Item2}");
}
Next step: Use a Dictionary<string, string> which is much better.

Iterate groups of user in AD and save them in list

I have a procedure that retrieves the user node out of AD:
public static void ConnectActiveDirectory()
{
List<string> lstGroups = new List<string>();
DirectoryEntry entry;
string user = "username";
string server = ConfigurationManager.AppSettings["ActiveDirectory.Server"];
entry = new DirectoryEntry(#"LDAP://" + server);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "sAMAccountName=" + user;
searcher.PropertiesToLoad.Add("MemberOf");
SearchResult result = searcher.FindOne();
}
The idea is to save all the groups in the list of strings without doing something like:
foreach (ResultPropertyValueCollection s in result.Properties.Values)
{
string groupname = null;
for (int i = 0; i < s.Count; i++)
{
dn = s[i].ToString();
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
groupname = dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1);
lstGroups.Add(groupname);
}
}
Is there any method that I can use in 'DirectorySearcher' Class?
Also, is there any way to delete the first Hashtable? the adspath one from the SearchResult object.
Instead of parsing the distinguished name by yourself, you can use the DirectoryEntry object to ask AD for the display name. For example:
var directoryEntry = new DirectoryEntry(#"LDAP://address");
var directorySearcher = new DirectorySearcher(directoryEntry);
directorySearcher.Filter = "samaccountname=user";
directorySearcher.PropertiesToLoad.Add("memberOf");
var result = directorySearcher.FindOne();
foreach (var i in result.Properties["memberOf"])
{
var group = new DirectoryEntry(#"LDAP://" + i);
Console.WriteLine(group.Properties["DisplayName"]);
}

Filter memberof groups of user

I have manage to get a list of the users memberof groups. I want to filter the groups so i only get the groups where "Hey" is included. Something like:
GroupHeyYou,
GroupHeyThere,
GroupYouKnow,
GroupWhatThe
and only returns GroupHeyYou and GroupHeyThere
This is my function:
public List<string> GetUserGroupMemberShip()
{
DirectoryEntry de = default(DirectoryEntry); //Binding object.
DirectorySearcher ds = default(DirectorySearcher); //Search object.
SearchResult sr = default(SearchResult);
List<string> groups = new List<string>();
string logonUserName = Environment.UserName;
string logonServer = (System.Environment.GetEnvironmentVariable("logonserver")).Remove(0, 2);
string activeDirectoryPath = "LDAP://" + logonServer + "." + System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
try
{
de = new DirectoryEntry(activeDirectoryPath);
ds = new DirectorySearcher(de, "(sAMAccountName=" + logonUserName + ")");
sr = ds.FindOne();
if (null != sr)
{
DirectoryEntry deUser = new DirectoryEntry(sr.Path);
object obGroups = deUser.Invoke("Groups");
foreach (object ob in (IEnumerable)obGroups)
{
DirectoryEntry deGroups = new DirectoryEntry(ob);
groups.Add(deGroups.Name);
}
}
}
catch (Exception)
{
return null;
}
return groups;
}
how can i use a filter to do that?
var filteredGroup = groups.FindAll(item =>
{
return item.Contains("Hey");
});

Categories

Resources