Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a specific field from output of tasklist on the windows command line

I ran the following command on the windows command prompt

C:>tasklist /fi "Imagename eq BitTorrent.exe"

The output of which is

Image Name            PID      Session Name       Session #    Mem Usage
==================  ======== =================   ===========   =========
BitTorrent.exe        6164      Console                   3     24,144K

I need to extract only one field, the PID, i.e. the number 6164 from the above output.

How do I achieve this ? More generally, how do I extract a subset(1/more) of the fields from the output of a command on the windows command line ?

like image 979
ashish makani Avatar asked Nov 22 '12 07:11

ashish makani


People also ask

What is tasklist command in cmd?

Displays a list of currently running processes on the local computer or on a remote computer. Tasklist replaces the tlist tool. Note. This command replaces the tlist tool.

How do you pipe the output of a command to a file in Windows?

To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.

Is tasklist a command-line tool?

Tasklist is a tool that displays a list of the processes that are running on either a local or remote machine.


2 Answers

Similar to previous answers, but uses specific switches in tasklist to skip header and behave correctly irrespective of spaces in image names:

for /f "tokens=2 delims=," %F in ('tasklist /nh /fi "imagename eq BitTorrent.exe" /fo csv') do @echo %~F

(as run directly from cmd line, if run from batch replace %F with %%F

like image 91
wmz Avatar answered Oct 27 '22 06:10

wmz


the easiest way is with using WMIC:

c:\>wmic process where caption="BitTorrent.exe" get  ProcessId

EDIT: As the WMIC is not part of home editions of windows:

for /f "tokens=1,2 delims= " %A in ('tasklist /fi ^"Imagename eq cmd.exe^" ^| find ^"cmd^"') do echo %B

Here is used CMD of the caption.You can change it in the find and tasklist parameters. If this used in batch file you'll need %%B and %%A

like image 20
npocmaka Avatar answered Oct 27 '22 06:10

npocmaka