I'm using this C# code to get the Command Line parameters of a running process:
public static void GetProcessesCommandLine(string processName)
{
string query = $@"SELECT CommandLine,ProcessId FROM Win32_Process WHERE Name = '{processName}'";
using (var searcher = new ManagementObjectSearcher(query))
using (var collection = searcher.Get())
{
foreach (ManagementObject item in collection)
{
Console.WriteLine($"--- TESTING PROCESS {item["ProcessId"]} ---");
var commandLine = item["CommandLine"];
if(commandLine == null)
{
Console.WriteLine("WARNING: command line is NULL");
}
else
{
Console.WriteLine($"CommandLine is: {commandLine}");
}
}
}
}
The problem is that the command line property turns out to be NULL in some cases, and I'm struggling to understand when and why this happens.
Initially I thought that it had something to do with the user that was running the code, and that the command line was NULL for processes that did not belong to that user. However, this does not seem to be the case upon further testing. For example, here I have the following situation:
As you can see, I have 4 instances of explorer.exe
all started by user edsep
, and.if I run the code above as user edsep
I get all the command lines correctly. However, if I run the code as a different user, this is the output I get:
As you can see, the command line is not NULL
on just one of the four processes. What is going on here? Why that process in particular works and the others don't? What are the rules here?
EDIT: another test, because there were some doubts about testing with explorer.exe. Here I have several instances of Chrome that are running under user edsep
:
If I run the code above as a different user, here's what I get:
As you can see, I get the command line for only 3 (apparently random?) processes out of 15... why?