Find my own process ID in VBScript

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

    I just found this thread that partly solved my problem. Thank you all.

    "the code is unable to determine which process ID belongs to which script" : true, but as this is the first task that your script must achieve , you can keep the Pid that has the shortest lifetime.

     Set com = CreateObject("Wscript.Shell")
    
     Set objSWbemServices = GetObject ("WinMgmts:Root\Cimv2")
     Set colProcess = objSWbemServices.ExecQuery ("Select * From Win32_Process")
     dim toto, thisPid
    
     thisPid=""
     toto=200 ' just a high value like 200sec 
     For Each objProcess In colProcess
    
         If InStr (objProcess.CommandLine, WScript.ScriptName) <> 0  Then
            Ptime=((Cdbl(objProcess.UserModeTime)+Cdbl(objProcess.KernelModeTime))/10000000)
            if toto > Ptime then
                toto = Ptime
                thisPid = objProcess.ProcessId
            End If
         End If
     Next
    
     If thisPid="" then
        WScript.Echo "unable to get the PID"
     Else
        WScript.Echo "PID of this script : "&thisPid
     End If
    

    Except if you fired scripts quicker more than each one can retrieve their Pid, everything must be ok.

提交回复
热议问题