Find my own process ID in VBScript

后端 未结 10 1038
小蘑菇
小蘑菇 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:14

    Here's an even better code snippet:

          ' ***********************************************************************************************************
          ' lng_MyProcessID finds and returns my own process ID. This is excruciatingly difficult in VBScript. The
          ' method used here forks "cmd /c pause" with .Exec, and then uses the returned .Exec object's .ProcessID 
          ' attribute to feed into WMI to get that process's Win32_Process descriptor object, and then uses THAT
          ' WMI Win32_Process descriptor object's .ParentProcessId attribute, which will be OUR Process ID, and finally
          ' we terminate the waiting cmd process. Execing cmd is what causes the brief cmd window to flash at start up,
          ' and I can' figure out out how to hide that window.
    
          ' returns: My own Process ID as a long int; zero if we can't get it.
          ' ************************************************************************************************************
    
          Function lng_MyProcessID ()
    
            lng_MyProcessID = 0                     ' Initially assume failure
    
            If objWMIService Is Nothing Then Exit Function      ' Should only happen if in Guest or other super-limited account
    
            Set objChildProcess = objWshShell.Exec ( """%ComSpec%"" /C pause" ) ' Fork a child process that just waits until its killed
    
            Set colPIDs= objWMIService.ExecQuery ( "Select * From Win32_Process Where ProcessId=" & objChildProcess.ProcessID,, 0 )
    
            For Each objPID In colPIDs                  ' There's exactly 1 item, but .ItemIndex(0) doesn't work in XP
    
              lng_MyProcessID = objPID.ParentProcessId          ' Return child's parent Process ID, which is MY process ID!
    
            Next
    
            Call objChildProcess.Terminate()                ' Terminate our temp child
    
          End Function ' lng_MyProcessID
    

提交回复
热议问题