Option Explicit
Dim intPID
Dim colItems, objItem, objWMIService, wshShell
Dim strCommand, strTitle
If WScript.Arguments.Count > 0 Then Syntax
On Error Resume Next
strTitle = Rnd( Second( Now ) ) & " " & FormatDateTime( Now, vbShortTime )
strCommand = "cmd.exe /k title " & strTitle
' Spawn a child process
Set wshShell = CreateObject( "WScript.Shell" )
wshShell.Run strCommand, 7, False
If Err Then WScript.Quit -1
Set wshShell = Nothing
Set objWMIService = GetObject( "winmgmts://./root/cimv2" )
' Get the newly spawned process' parent process ID
Set colItems = objWMIService.ExecQuery( "SELECT * FROM Win32_Process WHERE CommandLine LIKE '%cmd.exe% /k title " & strTitle & "'" )
If Err Then WScript.Quit -1
For Each objItem In colItems
intPID = objItem.ParentProcessId
If Err Then WScript.Quit -1
' Terminate the spawned process
objItem.Terminate
If Err Then WScript.Quit -1
Next
' The parent of that parent process is the current script engine
Set colItems = objWMIService.ExecQuery( "SELECT * FROM Win32_Process WHERE ProcessId=" & intPID )
If Err Then WScript.Quit -1
For Each objItem In colItems
intPID = objItem.ParentProcessId
If Err Then WScript.Quit -1
Next
Set colItems = Nothing
Set objWMIService = Nothing
On Error Goto 0
WScript.Echo intPID
WScript.Quit intPID
Sub Syntax
Dim strMsg
strMsg = "GetMyPID.vbs, Version 1.00" _
& vbCrLf _
& "Return this script's process ID, both on screen and as ""errorlevel""" _
& vbCrLf & vbCrLf _
& "Usage: CSCRIPT.EXE //NoLogo GetMyPID.vbs" _
& vbCrLf & vbCrLf _
& "Note: The script's return code (""errolevel"") equals the PID, or" _
& vbCrLf _
& " will be -1 in case of errors." _
& vbCrLf & vbCrLf _
& "Written by Rob van der Woude" _
& vbCrLf _
& "http://www.robvanderwoude.com"
WScript.Echo strMsg
WScript.Quit -1
End Sub