开发者

Counting process instances using Batch

Im trying to count the number of php-cgi.exe processes on my server 200开发者_运维知识库3 system using "tasklist" and grep for windows. I would like to avoid writing to any temp files.

call set _proc_cnt = tasklist /fi "Imagename eq php-cgi.exe" /nh /fo CSV| grep -c -e "php-cgi"
echo %_proc_cnt%
pause

Heres what I get when I run that

C:\Users\gm\Desktop>call set _proc_cnt = tasklist /fi "Imagename eq php-cgi.exe" /nh /fo CSV  | grep -c -e "php-cgi"
0

C:\Users\gm\Desktop>echo
ECHO is on.

C:\Users\gm\Desktop>pause
Press any key to continue . . .

Does anyone have any tips on why that doesnt work?


I am not sure if your requirements are strict on this being done in a batch file, but this is pretty easy using a VBS script and WMI.

Create a new file with a vbs extension and add the below to the file. The script will present a dialog with the number of cmd.exe instances.

Option Explicit
Dim objWMIService, processItems, processName

processName = "cmd.exe"
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")

Set processItems = objWMIService.ExecQuery("Select * from Win32_Process where Name='"  & processName & "'")

Wscript.Echo processName & ": " & processItems.Count


Heres what I ended up doing. I used the script linuxuser27 posted and a nice FOR loop to get a process instance count stored in a variable.

FOR /F "tokens=*" %%i IN ('%~dp0count_proc.vbs php-cgi.exe') DO SET _PROC_COUNT=%%i
ECHO %_PROC_COUNT%
PAUSE



And here is the vbscript linuxuser27 posted that I tweaked just a little so that I could pass in whatever process name I wanted to count as a parameter (also removed the processName bit). I simply called this proc_count.vbs as you can see in the source for my batch file.

Option Explicit
Dim objWMIService, processItems, processName

processName = Wscript.Arguments(0)
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")

Set processItems = objWMIService.ExecQuery("Select * from Win32_Process where Name='"  & processName & "'")

Wscript.Echo processItems.Count
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜