Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 792
E235 Avatar asked Oct 12 '14 23:10

E235


People also ask

How do I find the PID of a process in Unix?

A process is nothing but running instance of a program and each process has a unique PID on a Unix-like system. The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.

How do I get PID in PowerShell?

To find the PID of a process, type Get-Process . Indicates that the UserName value of the Process object is returned with results of the command. Specifies one or more process objects. Enter a variable that contains the objects, or type a command or expression that gets the objects.


2 Answers

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 

Update for PowerShell Core

In version 6, Windows PowerShell started towards cross platform support with PowerShell Core based on .NET Core. This led to many changes in cmdlets that were Windows-centric and some being left out completely. WMI is a Windows only technology, so its cmdlets (e.g. Get-WmiObject) were not ported over. However, its features are available via CIM cmdlets (e.g. Get-CimInstance) here is a version that will work on PowerShell 6+:

$id = Get-CimInstance -Class Win32_Service -Filter "Name LIKE 'WinDefend'" |        Select-Object -ExpandProperty ProcessId  $process = Get-Process -Id $id 
like image 195
Mike Zboray Avatar answered Oct 10 '22 03:10

Mike Zboray


$p=Tasklist /svc /fi "SERVICES eq windefend" /fo csv | convertfrom-csv $p.PID 
like image 37
walid toumi Avatar answered Oct 10 '22 04:10

walid toumi