问题描述
我正在使用以下代码片段来确定我的 vbscript 正在运行的进程 ID:
I'm using the following code snippet to determine what process ID my vbscript is running as:
On Error Resume Next
Dim iMyPID : iMyPID = GetObject("winmgmts:rootcimv2").Get("Win32_Process.Handle='" & CreateObject("WScript.Shell").Exec("mshta.exe").ProcessID & "'").ParentProcessId
If Err.Number <> 0 Then Call Handle_Error(Err.Description)
On Error Goto 0
在我的 Windows 7(32 位)机器上,这大约有 90% 的时间有效,并且 iMyPID
包含当前运行脚本的进程 ID.但是,有 10% 的时间 Handle_Error
被调用并显示错误消息SWbemServicesEX:未找到".
On my Windows 7 (32-bit) machine this works about 90% of the time and iMyPID
contains the process ID of the currently running script. However 10% of the time Handle_Error
gets called with the error message "SWbemServicesEX: Not found".
最近运行 Windows 7(64 位)的其他人报告说 Handle_Error
总是被调用并显示错误消息内存不足".这似乎是一条疯狂的错误消息,只是为了找出您自己的进程 ID!
Recently someone else running Windows 7 (64-bit) reported that Handle_Error
always gets called with the error message "Out of memory". This seems an insane error message just to find out your own process ID!
谁能推荐一个更好的方法?
Can anyone recommend a better way of doing this?
推荐答案
mshta 立即终止自身.使用 WMI 服务获取父进程 ID 可能为时已晚.
因此,我会使用类似的方法来消除并发脚本进程.
mshta terminates itself immediately. Maybe it's too late to achieve parent process id by using WMI service.
So, I'd use something like this to eliminate concurrent script processes.
- 生成随机的东西.
- 确定可以安装在每个系统上的应用程序,从不自行终止(例如,带有/k 参数的命令提示符).
- 使用生成的随机参数以隐藏模式启动应用程序 (WshShell.Run).
- 等待几毫秒
- 使用命令行参数值查询正在运行的进程.
- 获取 ParentProcessId 属性.
Function CurrProcessId
Dim oShell, sCmd, oWMI, oChldPrcs, oCols, lOut
lOut = 0
Set oShell = CreateObject("WScript.Shell")
Set oWMI = GetObject(_
"winmgmts:{impersonationLevel=impersonate}!\.
ootcimv2")
sCmd = "/K " & Left(CreateObject("Scriptlet.TypeLib").Guid, 38)
oShell.Run "%comspec% " & sCmd, 0
WScript.Sleep 100 'For healthier skin, get some sleep
Set oChldPrcs = oWMI.ExecQuery(_
"Select * From Win32_Process Where CommandLine Like '%" & sCmd & "'",,32)
For Each oCols In oChldPrcs
lOut = oCols.ParentProcessId 'get parent
oCols.Terminate 'process terminated
Exit For
Next
CurrProcessId = lOut
End Function
Dim ProcessId
ProcessId = CurrProcessId 'will remain valid indefinitely
WScript.Echo ProcessId
这篇关于在 VBScript 中查找我自己的进程 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!