如何从 Windows 命令行上的任务列表输出中提取特定字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13507902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:04:34  来源:igfitidea点击:

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

windowsbatch-filecommand-linecmdtasklist

提问by ashish makani

I ran the following command on the windows command prompt

我在 windows 命令提示符下运行了以下命令

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.

我只需要从上面的输出中提取一个字段,即 PID,即数字 6164。

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 ?

我如何实现这一目标?更一般地说,如何从 windows 命令行上的命令输出中提取字段的子集(1/更多)?

回答by wmz

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

与之前的答案类似,但使用特定的开关tasklist来跳过标题并正确运行,而不管图像名称中的空格:

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 %Fwith %%F

(直接从 cmd 行运行,如果从批处理运行替换%F%%F

回答by npocmaka

the easiest way is with using WMIC:

最简单的方法是使用 WMIC:

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

EDIT:As the WMIC is not part of homeeditions of windows:

编辑:由于 WMIC 不是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 %%Band %%A

这里使用了标题的CMD。您可以在查找和任务列表参数中更改它。如果这在批处理文件中使用,您将需要%%B%%A

回答by ElektroStudios

You can use wmic command to not filter the output:

您可以使用 wmic 命令不过滤输出:

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.

PS:请记住,如果应用程序文件名包含空格,则需要正确设置令牌。