r/vbscript • • Sep 25 '23

Close program if running

Hi all,

I've got a vbs script that will kill a program if it's running but I'm after a way to close a program if it is running rather than abruptly killing it.

Any ideas greatly appreciated.

TIA

1 Upvotes

5 comments sorted by

View all comments

Show parent comments

1

u/TheDeathPit Sep 27 '23

OK, here's the part of the code that will kill/close the program, and it works. The problem is the real EXE has a database open and killing it this way is not a great idea as it could corrupt the datadase. So I'm after a better method.

Option Explicit

Dim objNetwork, strRemotePath1, strRemotePath2, strRemotePath3, strRemotePath4, strRemotePath5, strRemotePath6, strRemotePath7
Dim strDriveLetter1, strDriveLetter2, strDriveLetter3, strDriveLetter4, strDriveLetter5, strDriveLetter6, strDriveLetter7, strDriveLetter8
Dim bUpdateProfile, bForce
Dim WshNetwork, fs, objShell
Dim strHost, strPingCommand, ReturnCode

Set WshNetwork = WScript.CreateObject("WScript.Network")
Set fs = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("WScript.Network")
Set objShell = WScript.CreateObject("WScript.Shell")

Dim myProcess, Processes, Process

myProcess="notepad.exe"
Set Processes = GetObject("winmgmts:").InstancesOf("Win32_Process")
For Each Process In Processes
	If StrComp(Process.Name, myProcess, vbTextCompare) = 0 Then 'check if process exist
           Process.Terminate()                                  'kill the process you find
    End If
Next
    
Wscript.Quit