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

时间:2022-01-07 01:22:35

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?

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

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

2 个解决方案

#1


6  

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.

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

#2


2  

Some options:

  • PsList from Microsoft
  • 来自Microsoft的PsList

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

  • Cygwin (for ps)
  • Cygwin(适用于ps)

  • the resource kit (for ps.vbs)
  • 资源工具包(适用于ps.vbs)

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

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

#1


6  

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.

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

#2


2  

Some options:

  • PsList from Microsoft
  • 来自Microsoft的PsList

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

  • Cygwin (for ps)
  • Cygwin(适用于ps)

  • the resource kit (for ps.vbs)
  • 资源工具包(适用于ps.vbs)

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

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