1

I'm trying to get a process ID by means of the process's execution-path. For that I'm executing the below Powershell command which runs perfectly in Powershell's console:

(Get-Process |  Where-Object {$_.Path -eq 'C:\WINDOWS\system32\winlogon.exe'}).Id

But executing the same through C# is giving no results. below is the code snippet I'm following:

string cmd = "(Get-Process |  Where-Object {{$_.Path -eq '{0}'}}).Id";
string path = @"C:\WINDOWS\system32\winlogon.exe";
string finalCmd = string.Format(cmd, System.IO.Path.GetFullPath(path));

powershell.Runspace = runspace;
powershell.AddScript(finalCmd);
var result = powershell.Invoke();

I'm using double-culry-braces for escape sequence. But still powershell.Invoke() returns nothing but null. Is there any other way to get the Process Id with its executable path?

My ultimate goal is that I should be able to push an application (MSI installer) to all the PCs in network through Active Directory(irrespective of x86/x64) and I should get the Process Ids for the given executable path. Thanks for the suggestions but in my case I need a generic solution which should work seamlessly for both x86 and x64.

Nani
  • 1,148
  • 3
  • 20
  • 35
  • Possible duplicate of [Invoking a Powershell script in C# results returning 0](https://stackoverflow.com/questions/23675422/invoking-a-powershell-script-in-c-sharp-results-returning-0) – Samvel Petrosov Aug 10 '18 at 07:25
  • 1
    Uncheck the Prefer 32 Bit checkbox and you will get the result. http://take.ms/kAbBA – Samvel Petrosov Aug 10 '18 at 07:26

1 Answers1

0

Doesn't seem like you need to use Powershell here. .NET code can query processes directly.

Something like:

Process.GetProcesses().Where(p=>p.MainModule.FileName==path)

should return you an enumerable of all matching processes, from which you can easily retrieve their IDs. And decide what to do if you find more than one!

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • thanks for the idea it is hopeful but I'm getting 'access denied' exception to get Process ID of a process which I have started from an admin-privileged command prompt. any suggestions to overcome this? – Nani Aug 14 '18 at 18:25
  • @N - you cannot circumvent security controls by clever coding. If you want to interact with code running under admin privileges, you need to have admin privileges yourself (or for it to expose a custom control point that it tries to secure itself) – Damien_The_Unbeliever Aug 14 '18 at 18:50
  • I have already tried running my application with admin privileges by choosing Run As Administrator, even tried running through Visual Studio opening the VS with Run As Administrator but still getting 'Access Denied' – Nani Aug 16 '18 at 05:27