1

within a vb script, I want to assign a variable with the process id of the cmd.exe in which the vb script is running. Is there any command?

2 Answers2

2

Below is the example VB script procedure returning parent process caption and id:

GetParentProcessInfo sCaption, sProcessId

MsgBox "Parent Process Caption '" & sCaption & "'" & vbCrLf & "Parent Process Id '" & sProcessId & "'"

Sub GetParentProcessInfo(sCaption, sProcessId)
    With GetObject("winmgmts:\\.\root\CIMV2:Win32_Process.Handle='" & CreateObject("WScript.Shell").Exec("rundll32 kernel32,Sleep").ProcessId & "'")
        With GetObject("winmgmts:\\.\root\CIMV2:Win32_Process.Handle='" & .ParentProcessId & "'")
            With GetObject("winmgmts:\\.\root\CIMV2:Win32_Process.Handle='" & .ParentProcessId & "'")
                sCaption = .Caption
                sProcessId = .ProcessId
            End With
        End With
        .Terminate
    End With
End Sub
omegastripes
  • 12,351
  • 4
  • 45
  • 96
  • Thanks. I am new vb script. I have to write a vbs that kills all the cmd.exe except the one in which the vb script is going to run. Below is the code which I was trying. – bharathi priya T Aug 04 '16 at 12:19
  • Set WshShell = WScript.CreateObject("WScript.Shell") Set a = WshShell.Exec(cmd /c "wmic process get parentprocessid,name|find WMIC") x = a.StdOut.ReadLine Wscript.Echo x pid = Right(x,4) Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'cmd.exe' and ProcessID != &abc") For Each item In colProcesses item.terminate() Next – bharathi priya T Aug 04 '16 at 12:30
  • 1
    @bharathipriyaT please don't post this as the comments, but add all these details into your question by editing it. Describe how does your code works, what's wrong and what is the expected behavior. Then I may suggest some code. – omegastripes Aug 04 '16 at 13:26
  • This solution has the advantage that it doesn't use a console program. In former times I experienced big trouble when to many console programs were executed on a disconnected terminal server session (they had all been properly terminated). rundll32 instead is a regular windows application (no console window shown), so this error will not appear. – David Gausmann Jun 29 '17 at 14:58
0

I used this to get a scripts parent process id.

Function GetParentPid()
    GetParentPid=GetObject("winmgmts:\\.\root\CIMV2").ExecQuery("Select * From Win32_Process Where CommandLine Like '%" &Wscript.ScriptName& "%'").ItemIndex(0).ParentProcessId
End Function

Wscript.Echo GetParentPid()