Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for getmypid.vbs

(view source code of getmypid.vbs as plain text)

  1. Option Explicit
  2. Dim intPID
  3. Dim colItems, objItem, objWMIService, wshShell
  4. Dim strCommand, strTitle
  5.  
  6. If WScript.Arguments.Count > 0 Then Syntax
  7.  
  8. On Error Resume Next
  9.  
  10. strTitle   = Rnd( Second( Now ) ) & " " & FormatDateTime( Now, vbShortTime )
  11. strCommand = "cmd.exe /k title " & strTitle
  12.  
  13. ' Spawn a child process
  14. Set wshShell = CreateObject( "WScript.Shell" )
  15. wshShell.Run strCommand, 7, False
  16. If Err Then WScript.Quit -1
  17. Set wshShell = Nothing
  18.  
  19. Set objWMIService = GetObject( "winmgmts://./root/cimv2" )
  20.  
  21. ' Get the newly spawned process' parent process ID
  22. Set colItems = objWMIService.ExecQuery( "SELECT * FROM Win32_Process WHERE CommandLine LIKE '%cmd.exe% /k title " & strTitle & "'" )
  23. If Err Then WScript.Quit -1
  24. For Each objItem In colItems
  25. 	intPID = objItem.ParentProcessId
  26. 	If Err Then WScript.Quit -1
  27. 	' Terminate the spawned process
  28. 	objItem.Terminate
  29. 	If Err Then WScript.Quit -1
  30. Next
  31.  
  32. ' The parent of that parent process is the current script engine
  33. Set colItems = objWMIService.ExecQuery( "SELECT * FROM Win32_Process WHERE ProcessId=" & intPID )
  34. If Err Then WScript.Quit -1
  35. For Each objItem In colItems
  36. 	intPID = objItem.ParentProcessId
  37. 	If Err Then WScript.Quit -1
  38. Next
  39.  
  40. Set colItems      = Nothing
  41. Set objWMIService = Nothing
  42.  
  43. On Error Goto 0
  44.  
  45. WScript.Echo intPID
  46. WScript.Quit intPID
  47.  
  48.  
  49. Sub Syntax
  50. 	Dim strMsg
  51. 	strMsg = "GetMyPID.vbs,  Version 1.00" _
  52. 	       & vbCrLf _
  53. 	       & "Return this script's process ID, both on screen and as ""errorlevel""" _
  54. 	       & vbCrLf & vbCrLf _
  55. 	       & "Usage:  CSCRIPT.EXE //NoLogo GetMyPID.vbs" _
  56. 	       & vbCrLf & vbCrLf _
  57. 	       & "Note:   The script's return code (""errolevel"") equals the PID, or" _
  58. 	       & vbCrLf _
  59. 	       & "        will be -1 in case of errors." _
  60. 	       & vbCrLf & vbCrLf _
  61. 	       & "Written by Rob van der Woude" _
  62. 	       & vbCrLf _
  63. 	       & "http://www.robvanderwoude.com"
  64. 	WScript.Echo strMsg
  65. 	WScript.Quit -1
  66. End Sub
  67.  

page last modified: 2024-04-16; loaded in 0.0052 seconds