windows 在批处理文件中,如何判断进程是否正在运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/302609/
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-15 11:38:06  来源:igfitidea点击:

Inside a batch file, how can I tell whether a process is running?

windowsbatch-fileprocess

提问by JosephStyons

I'd like to write a batch file that checks to see if a process is running, and takes one action if it is, and another action if it isn't.

我想编写一个批处理文件来检查进程是否正在运行,如果是,则执行一个操作,如果不是,则执行另一个操作。

I know I can use tasklist to list all running processes, but is there a simpler way to directly check on a specific process?

我知道我可以使用 tasklist 列出所有正在运行的进程,但是有没有更简单的方法来直接检查特定进程?

It seems like this should work, but it doesn't:

看起来这应该有效,但它没有:

tasklist /fi "imagename eq firefox.exe" /hn | MyTask
IF %MyTask%=="" GOTO DO_NOTHING
'do something here
:DO_NOTHING

Using the solution provided by atzz, here is a complete working demo:

使用 atzz 提供的解决方案,这里是一个完整的工作演示:

Edit: Simplified, and modified to work under both WinXP and Vista

编辑:简化和修改以在 WinXP 和 Vista 下工作

echo off

set process_1="firefox.exe"
set process_2="iexplore.exe"
set ignore_result=INFO:

for /f "usebackq" %%A in (`tasklist /nh /fi "imagename eq %process_1%"`) do if not %%A==%ignore_result% Exit
for /f "usebackq" %%B in (`tasklist /nh /fi "imagename eq %process_2%"`) do if not %%B==%ignore_result% Exit

start "C:\Program Files\Internet Explorer\iexplore.exe" www.google.com

采纳答案by atzz

You can use "for /f" construct to analyze program output.

您可以使用“for /f”构造来分析程序输出。

set running=0
for /f "usebackq" %%T in (`tasklist /nh /fi "imagename eq firefox.exe"`) do set running=1

Also, it's a good idea to stick a

此外,坚持一个好主意

setlocal EnableExtensions

at the begginning of your script, just in case if the user has it disabled by default.

在脚本开始时,以防万一用户默认禁用它。

回答by Lou Franco

Some options:

一些选项:

  • PsList from Microsoft
  • 来自微软的 PsList

http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/win2kcommands_0401.html#ps

http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/win2kcommands_0401.html#ps

  • Cygwin (for ps)
  • the resource kit (for ps.vbs)
  • Cygwin(用于 ps)
  • 资源包(用于 ps.vbs)

http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/win2kcommands_0401.html#ps

http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/win2kcommands_0401.html#ps

  • Powershell for get-process.
  • 用于获取进程的 Powershell。