1

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

4

2 回答 2

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该进程将包含C:\example.xls在进程命令行属性中。

于 2013-01-01T15:15:59.240 回答
1

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

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

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

附录:

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

#Get process list from Server01, assuming you have sufficient rights
Get-WMIObject win32_process -Computername server01
于 2013-01-01T14:32:27.480 回答