VBScript get process id by process name or program executable name - windows

I need to do exactly as I asked in the question for any program that I have just started from my VBScript.
I am starting the System Properties program from VBscript as below:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "SystemPropertiesAdvanced.exe"
WScript.Sleep 1000
Now I want to get the process id of SystemPropertiesAdvanced.exe program, how can I do that ?
I would like to do this purely by VBScript without mix coding as much as possible.

Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process where name='Calculator.exe'")
'msgbox colitems
For Each objItem in colItems
msgbox objItem.name & " " & objItem.ProcessID & " " & objItem.CommandLine
If objItem.name = "Calculator.exe" then objItem.terminate
Next
This uses WMI to query for Calculator.exe and then terminates it.

This is how to to start process and get processID with WshShell Object:
Dim sh : Set sh = CreateObject("WScript.Shell")
Set Rtn = sh.Exec("SystemPropertiesAdvanced.exe") 'write the full path of application
WScript.Sleep 1000 'stop script 1 sec waiting run the App
MsgBox "my App PID : " & Rtn.ProcessID 'Process ID for App
OR use WMI to start process and get the processID
set process = GetObject("winmgmts:Win32_Process")
process.Create "SystemPropertiesAdvanced.exe",null,null,processid
MsgBox "my App PID : " & Processid

Related

vbs run program as admin and with a priority level

I want on startup to launch a vbs script that will launch another program as administrator and set the priority of that program to above normal or high priority.
I currently have made it to launch the program as admin but am stuck on setting the process level.
Set app = CreateObject("Shell.Application")
app.ShellExecute """d:\SYNC\Dropbox\PORTABLE_PROGRAMS\ahk\Navigare\KeyboardEnchancer\KeyboardEnchancer.exe""", , , "runas", 3
I edited the answer to address your permission problem, the script now self-elevates to run as administrator, more info at: How to Automatically Elevate a Vbscript to Run it as Administrator?. Tested and working flawlessly on my machine.
If WScript.Arguments.length = 0 Then
Set objShell = CreateObject("Shell.Application")
'Pass a bogus argument, say [ uac]
objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
Set objShell= CreateObject("Shell.Application")
strComputer = "."
Const HIGH_PRIORITY = 128
processName = "notepad.exe" ' The process name of your app
appName = "C:\Windows\System32\notepad.exe" ' The app you want to run
objShell.ShellExecute appName, , , "runas", 1
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = '" & processName & "'")
For Each p in colProcesses
p.SetPriority(HIGH_PRIORITY)
Next
End If
More info at: SetPriority method of the Win32_Process class and ShellExecute method.
I used this to change a script's own priority from within its execution:
Sub SetPriority()
Const IDLE = 64, BELOW_NORMAL = 16384, NORMAL = 32, ABOVE_NORMAL = 32768, HIGH_PRIORITY = 128, REAL_TIME = 256
GetObject("winmgmts:\\.\root\CIMV2").ExecQuery("Select * From Win32_Process Where CommandLine Like '%" &Wscript.ScriptName& "%'").ItemIndex(0).SetPriority(HIGH_PRIORITY)
End Sub
Call SetPriority()
This answers the question... as admin with priority.
dim sFile: sFile=chr(34)& "C:\Windows\System32\notepad.exe" &chr(34)
CreateObject("Shell.Application").ShellExecute "cmd.exe","/c START /HIGH /B """" " &sFile, ,"runas", 1

Get new created process processID Vbscript

I am creating this snippet that executes a calc.exe process and report its processID
Option Explicit
Dim objWMIService, objProcess, objCalc
Dim strShell, objProgram, strComputer, strExe ,oMethod, svc, sQuery, cproc, iniproc, ProcID
strComputer = "."
strExe = "Calc.exe"
' Connect to WMI
set objWMIService = getobject("winmgmts://"_
& strComputer & "/root/cimv2")
' Obtain the Win32_Process class of object.
Set objProcess = objWMIService.Get("Win32_Process")
Set objProgram = objProcess.Methods_( _
"Create").InParameters.SpawnInstance_
objProgram.CommandLine = strExe
'Execute the program now at the command line.
Set strShell = objWMIService.ExecMethod( _
"Win32_Process", "Create", objProgram)
ProcID = strShell.ProcessId
WScript.echo "The process ID is" &ProcID
I have being validating the process id of the calc.exe opened with proces explorer but it does not match to the info that i am getting.
¡Any ideas about, ¿why I am getting the wrong process id?
The easy way to get process id:
set process = GetObject("winmgmts:Win32_Process")
process.Create "calc.exe",null,null,processid
wscript.echo " PID : " & Processid

How to get running application name by vbscript

I would like to get the name list of running application by vbscript and kill the application by its main window title. Those applications should be listed on Task Manager -> Applications tab
Like this:
After searching from web, I found vbscript like this:
'FUNCTION
Function ListProcessRunning()
'This function can report names from
'TaskManager -> Processes
sComputerName = "."
Set objWMIService = GetObject("winmgmts:\\" & sComputerName & "\root\cimv2")
sQuery = "SELECT * FROM Win32_Process"
Set objItems = objWMIService.ExecQuery(sQuery)
'iterate all item(s)
For Each objItem In objItems
WScript.Echo objItem.Name
Next
End Function
This vbscript list all process names which are under Task Manager -> Processes tag like this:
Which is not what I want.
I also found this:
'FUNCTION
Function ListApplicationRunning()
'This function can report names from
'TaskManager -> Application
Set Word = CreateObject("word.application")
For Each x In Word.Tasks
WScript.Echo x.Name
Next
Word.Quit
Set Word = Nothing
End Function
Which really give me what I want but the problem is the server I am going to run this script has no Word so no word.application for vbscript and I am not able to install one for it.
My question is how to get the application name and kill the application by that name? I am not sure is it possible to do with vbscript only, may be a combination of vbscript and cmd is also okay.
In vbscript we can do something like that just give a try with it :
Option Explicit
Call KillProcessbyName("common-api.jar")
'*********************************************************************************
Sub KillProcessbyName(FileName)
On Error Resume Next
Dim WshShell,strComputer,objWMIService,colProcesses,objProcess
Set WshShell = CreateObject("Wscript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process")
For Each objProcess in colProcesses
If InStr(objProcess.CommandLine,FileName) > 0 Then
If Err <> 0 Then
MsgBox Err.Description,VbCritical,Err.Description
Else
objProcess.Terminate(0)
End if
End If
Next
End Sub
'**********************************************************************************
FOR /F "usebackq tokens=1-2" %i IN (`tasklist ^|findstr /b "notepad"`) DO taskkill /PID %j

Can anyone help me close this program in VBScript?

MsgBox ("Do you want to start the autoclicker?", vbOkOnly, "Autoclicker")
CreateObject("WScript.Shell").Run("""C:\Users\Henry\Desktop\Fun.vbs""")
MsgBox ("Do you want to stop the autoclicker?", vbOkOnly, "Autoclicker")
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objItem in colItems
'msgbox objItem.ProcessID & " " & objItem.CommandLine
If objItem.name = "Calculator.exe" then objItem.terminate
Next
This kills calculator.exe. Change it to wscript.exe. You might want to check command line if you just want to kill fun.vbs.
The following routine kills all processes whose command lines contain a specified string. The 3 lines below the routine are for testing it. We pause the routine by showing a message box and when you dismiss the message box, we kill the script instance, so the second message box doesn't show up. When you use it, you want to replace the last 3 lines with
KillProcesses "Fun.vbs"
I'd be careful using this and specify as much of the command line as possible to make sure I absolutely, positively match only the processes I want to terminate. You can modify the Task Manager and add a column to show the command line for every running process. In the routine below, the search in command line is case-insensitive.
Option Explicit
Sub KillProcesses(strPartOfCommandLine)
Dim colProcesses
Dim objProcess
Dim lReturn
' Get list of running processes using WMI
Set colProcesses = GetObject("winmgmts:\\.\root\cimv2").ExecQuery("Select * From Win32_Process")
For Each objProcess in colProcesses
If (Instr(1, objProcess.Commandline, strPartOfCommandLine, vbTextCompare) <> 0) Then
lReturn = objProcess.Terminate(0)
End If
Next
End Sub
Msgbox "Before being killed"
KillProcesses "KillProcesses.vbs"
Msgbox "After being killed"
I made before a script that ask you what vbscript did you want to kill and log the result into file.
So just, give a try :
Option Explicit
Dim Titre,Copyright,fso,ws,NomFichierLog,temp,PathNomFichierLog,OutPut,Count,strComputer
Copyright = "[© Hackoo © 2014 ]"
Titre = " Process "& DblQuote("Wscript.exe") &" running "
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject( "Wscript.Shell" )
NomFichierLog="Process_WScript.txt"
temp = ws.ExpandEnvironmentStrings("%temp%")
PathNomFichierLog = temp & "\" & NomFichierLog
Set OutPut = fso.CreateTextFile(temp & "\" & NomFichierLog,1)
Count = 0
strComputer = "."
Call Find("wscript.exe")
Call Explorer(PathNomFichierLog)
'***************************************************************************************************
Function Explorer(File)
Dim ws
Set ws = CreateObject("wscript.shell")
ws.run "Explorer "& File & "\",1,True
end Function
'***************************************************************************************************
Sub Find(MyProcess)
Dim colItems,objItem,Processus,Question
Set colItems = GetObject("winmgmts:").ExecQuery("Select * from Win32_Process " _
& "Where Name like '%"& MyProcess &"%' AND NOT commandline like '%" & wsh.scriptname & "%'",,48)
For Each objItem in colItems
Count= Count + 1
Processus = Mid(objItem.CommandLine,InStr(objItem.CommandLine,""" """) + 2) 'Extraction of the commandline script path
Processus = Replace(Processus,chr(34),"")
Question = MsgBox ("Did you want to stop this script : "& DblQuote(Processus) &" ?" ,VBYesNO+VbQuestion,Titre+Copyright)
If Question = VbYes then
objItem.Terminate(0)'Kill this process
OutPut.WriteLine DblQuote(Processus)
else
Count= Count - 1 'decrement the counter -1
End if
Next
OutPut.WriteLine String(100,"*")
OutPut.WriteLine count & Titre & " were stopped !"
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************

Wait for program to complete

To monitor the bandwidth usage and not to unnecessarily load programs in the start up,I want to execute the dumeter.exe then firefox.exe.When I shutdown firefox it should kill dumeter.I used the following code to start
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "c:\progra~1\dumeter\dumeter.exe"
WshShell.Run "c:\progra~1\mozill~1\firefox.exe
Need to run taskkill only when firefox is closed.Tried using a bat file but sometimes the dumeter starts and closes on its own does not wait.
WshShell.Run "taskkill /f /im dumeter.exe"
Set WshShell = Nothing
You can wait for a process to end by subscribing to the appropriate WMI event. Here's an example:
strComputer = "."
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
''# Create an event query to be notified within 5 seconds when Firefox is closed
Set colEvents = oWMI.ExecNotificationQuery _
("SELECT * FROM __InstanceDeletionEvent WITHIN 5 " _
& "WHERE TargetInstance ISA 'Win32_Process' " _
& "AND TargetInstance.Name = 'firefox.exe'")
''# Wait until Firefox is closed
Set oEvent = colEvents.NextEvent
More info here: How Can I Start a Process and Then Wait For the Process to End Before Terminating the Script?
Option Explicit
Const PROC_NAME = "<Process_You_Want_to_Check>"
Const SLEEP_INTERVAL_MS = 5000 '5 secs
Dim objWMIService
Dim colProcesses, objProcess, inteproc
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
inteproc = -1 'set in unknown state
Do Until inteproc = 0
Set colProcesses = objWMIService.ExecQuery(_
"Select * from Win32_Process where Name='" & PROC_NAME & "'")
inteproc = colProcesses.count
If inteproc > 0 then
WSCRIPT.ECHO "Process " & PROC_NAME & " is still runing, wait for " & SLEEP_INTERVAL_MS / 1000 & " seconds"
WScript.Sleep(SLEEP_INTERVAL_MS)
else
wscript.echo "Process " & PROC_NAME & " Finished. Continue running scripts"
End If
Loop

Resources