E235 E235 - 3 months ago 35
PowerShell Question

How to get process id by its service name with a script to variable

I have service named

WinDefend
and it runs on process
svchost.exe


There other many
svchost.exe
processes and I need to find a way to get its ID.

when I run
tasklist /svc
I can see:
enter image description here

I am not sure how can I get it.

I found this command but when I tried the
select "PID"
it gave me empty column.
enter image description here

I need to get the PID of the process to variable.

Answer

tasklist is just returning text, not actual objects that have properties you can access. You can use WMI to get this information instead:

$id = Get-WmiObject -Class Win32_Service -Filter "Name LIKE 'WinDefend'" | 
      Select-Object -ExpandProperty ProcessId

$process = Get-Process -Id $id
Comments