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

早过忘川 提交于 2019-12-18 00:48:48

问题


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 ?


回答1:


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




回答2:


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




回答3:


You can use wmic command to not filter the output:

wmic process where name="BitTorrent.exe" get processid | MORE +1

UPDATE: Another way:

@Echo OFF
FOR /F "tokens=2" %%# in ('tasklist /fi "Imagename eq winamp.exe" ^| MORE +3') do (Echo %%#)
Pause&Exit

PS: Remember you need to set right the tokens if the app filename contain spaces.



来源:https://stackoverflow.com/questions/13507902/how-to-extract-a-specific-field-from-output-of-tasklist-on-the-windows-command-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!