Find my own process ID in VBScript

后端 未结 10 1042
小蘑菇
小蘑菇 2020-11-28 14:49

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         


        
10条回答
  •  误落风尘
    2020-11-28 15:23

    To retrieve the own process ID of a VB Script you can rely on the property CreationDate of the Process object.

    At the moment a VB Script is started, the process that runs the script will have the latest CreationDate of all processes that runs the same script.

    In fact, it will have the highest CreationDate of all running processes.

    So, to get the PID, first thing to do is to search for the process with the highest CreationDate.

    'Searching for processes
    Dim strScriptName
    Dim WMI, wql
    Dim objProcess
    '
    'My process
    Dim datHighest
    Dim lngMyProcessId
    
    
    'Which script to look for ? 
    strScriptName = "WScript.exe"
    'strScriptName = "Notepad.exe"
    
    'Iniitialise 
    datHighest = Cdbl(0)
    
    Set WMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
    wql = "SELECT * FROM Win32_Process WHERE Name = '" & strScriptName & "'"
    '
    For Each objProcess In WMI.ExecQuery(wql)
      'The next If is not necessary, it only restricts the search to all processes on the current VB Script
      'If Instr(objProcess.CommandLine, WScript.ScriptName) <> 0 Then
        If objProcess.CreationDate > datHighest Then
          'Take the process with the highest CreationDate so far
          '  e.g. 20160406121130.510941+120   i.e. 2016-04-06 12h11m:30s and fraction
          datHighest = objProcess.CreationDate
          lngMyProcessId = objProcess.ProcessId
        End If
      'End If
    Next
    
    'Show The result
    WScript.Echo "My process Id = " & lngMyProcessId
    

提交回复
热议问题