我们如何识别由不同对象打开的两个excel.exe进程?

时间:2013-01-01 07:24:15

标签: powershell vbscript exe wsh

我有一个正在处理Excel工作簿的.vbs文件。现在假设一个情况arsie在系统中3 EXCEL.EXE进程正在运行。那么现在有什么办法可以找出main.vbs脚本打开哪一个?

2 个答案:

答案 0 :(得分:2)

即使你标记了这个powershell,这里只有一个VBS选项可能需要一些修改,这取决于你的Excel版本(我在这台电脑上有2003):

'Create Excel Application for demo purposes only
Dim ex: Set ex = CreateObject("Excel.Application")
Dim objWMIService, objProcess, colProcess
Dim strComputer, strList

strComputer = "." 'Change if you want to run on another computer

Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")

'Look only at Excel process name
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where NAME = 'EXCEL.exe'")

'Get the list of Processes, included only for demo purposes
For Each objProcess In colProcess
    strList = strList & vbCr & objProcess.commandline
Next
MsgBox strList ' Displayed "C:\Program Files\Microsoft Office\OFFICE11\EXCEL.EXE"
                          '"C:\Program Files\Microsoft Office\OFFICE11\EXCEL.EXE" / automation - Embedding
               ' Second row was the created Object.

'Find processes that match the Created Object format commandline
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where CommandLine Like '%EXCEL.exe"" /automation -Embedding'")
For Each objProcess In colProcess
    'Do something with process
    objProcess.Terminate
Next
'Next line will cause runtime error due to process already being terminated.
ex.Quit

与此类似的方法的优点在于,通过使用objProcess.Commandline,您可以找到发送到应用程序的命令行开关,您可以使用它来查明特定进程。例如,如果您有一个.bat文件打开了这样的Excel文件:start Excel.exe C:\example.xls该进程将在进程Commandline属性中包含C:\example.xls

答案 1 :(得分:1)

使用Get-WMIObject win32_process获取所有进程的列表。查看ParentProcessId成员以查看哪个进程生成了哪个Excel实例。

VBScripts是通过WScript或CScript执行的,因此您需要先查看正确的父级。

请注意Windows会回收流程ID。也就是说,在时间t0,pid 1000不一定是与时间t1相同的过程。

<强>附录:

使用-Computername开关为WMI查询指定另一台计算机。如果不存在-Computername开关,则假定为localhost。本地主机也称为.,它在上面的VBScript答案中使用。像这样,

#Get process list from Server01, assuming you have sufficient rights
Get-WMIObject win32_process -Computername server01