在VBScript中找到我自己的进程ID [英] Find my own process ID in VBScript

查看:104
本文介绍了在VBScript中找到我自己的进程ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码段来确定我的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:root\cimv2").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.但是,错误消息" SWbemServicesEX:未找到"会调用Handle_Error 10%的时间.

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.

  1. 生成随机事物.
  2. 确定可以在每个系统上安装的应用程序,永远不要自行终止(例如,带有/k参数的命令提示符).
  3. 使用生成的随机参数( WshShell.Run ).
  4. 等待几毫秒
  5. 使用命令行参数值查询正在运行的进程.
  6. 获取ParentProcessId属性.
  1. Generate random things.
  2. Determine an application which could be installed on each system, never terminates by itself (e.g. command prompt with /k parameter).
  3. Start the application in hidden mode with generated random argument (WshShell.Run).
  4. Wait a few milliseconds
  5. Query the running processes by using command line argument value.
  6. Get the ParentProcessId property.

Function CurrProcessId
    Dim oShell, sCmd, oWMI, oChldPrcs, oCols, lOut
    lOut = 0
    Set oShell  = CreateObject("WScript.Shell")
    Set oWMI    = GetObject(_
        "winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
    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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆