Find my own process ID in VBScript

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

    I like Kul-Tigin's idea (+1), and Asok Smith's idea (based on .Exec) deserve respect (+1), and it w'd been even better if .Exec run hidden process. So, to feed my curiosity, I also toyed with this and this's what I did.

    ts1 = Timer : res1 = CurrProcessId : te1 = Timer - ts1
    ts2 = Timer : res2 = ThisProcessId : te2 = Timer - ts2
    WScript.Echo "CurrProcessId", res1, FormatNumber(te1, 6), _
        vbCrLf & "ThisProcessId", res2, FormatNumber(te2, 6), _
        vbCrLf & "CurrProcessId / ThisProcessId = " & te1 / te2
    
    '> CurrProcessId 6946 0,437500
    '> ThisProcessId 6946 0,015625
    '> CurrProcessId / ThisProcessId = 28
    
    Function ThisProcessId
        ThisProcessId = 0
        Dim sTFile, oPrc
        With CreateObject("Scripting.FileSystemObject")
            sTFile = .BuildPath(.GetSpecialFolder(2), "sleep.vbs")
            With .OpenTextFile(sTFile, 2, True)
                .Write "WScript.Sleep 1000"
            End With
        End With
        With CreateObject("WScript.Shell").Exec("WScript " & sTFile)
            For Each oPrc In GetObject("winmgmts:\\.\root\cimv2").ExecQuery(_
            "Select * From Win32_Process Where ProcessId=" & .ProcessID)
            Exit For : Next
            ThisProcessId = oPrc.ParentProcessId
        End With
    End Function
    

    28 times faster(!), not bad :)

提交回复
热议问题