user1915934
user1915934

Reputation: 121

Close an application using VBScript

I was trying to open and close an application. I tried like this:

Dim App1 
Set App1 = CreateObject("WScript.Shell")
App1.Run("firefox")
App1.Quit

Firefox will open, but it will not close.

Error message:

object doesn't support this property or method

I referred InDesign Scripting how to quit application (not document)

Please tell me the procedure to close the application.

Upvotes: 6

Views: 81844

Answers (5)

Farouk
Farouk

Reputation: 1

Good work for this example:

Dim oShell : Set oShell = CreateObject("WScript.Shell")
oShell.Run """C:\My_Scripts\ddl.exe"" -p1 -c"

'some code

oShell.Run "taskkill /f /im ddl.exe", , True

Upvotes: 0

vr286
vr286

Reputation: 836

I observed a few ways:

  1. taskkill - Worked only if I try to kill the same process, as I run.

    Dim oShell : Set oShell = CreateObject("WScript.Shell")
    oShell.Run """C:\My_Scripts\ddl.exe"" -p1 -c"
    
    'some code
    
    oShell.Run "taskkill /f /im ddl.exe", , True
    
  2. SendKeys - Works for all app, if the window name is known.

    Dim oShell : Set oShell = CreateObject("WScript.Shell")
    filename = "C:\Some_file.txt - Notepad"
    act = oShell.AppActivate(fileName)
    oShell.SendKeys "% C"
    
  3. WMI object - 2 ways above worked good for me so I didn't try it. You can find an example here:

    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\.\root\cimv2")
    
    Set colProcessList = objWMIService.ExecQuery _
        ("Select * from Win32_Process Where Name = 'Chrome.exe'")
    
    Set oShell = CreateObject("WScript.Shell")
    For Each objProcess in colProcessList
        oShell.Run "taskkill /im chrome.exe", , True
    Next
    

Upvotes: 3

Stein Åsmul
Stein Åsmul

Reputation: 42126

Here is an alternative VBScript implementation:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colProcessList = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = 'Notepad.exe'")

For Each objProcess in colProcessList
    objProcess.Terminate()
Next

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

If you want to be able to terminate a process that way you need to use the Exec method instead of the Run method.

Set ff = CreateObject("WScript.Shell").Exec("firefox")
'you do stuff
ff.Terminate

Upvotes: 7

david
david

Reputation: 2638

Firefox is not a COM object. There is no Firefox COM object. Firefox does not want you to use COM. Or NET. Or Microsoft. That is why you could not create a Firefox object, so you created a WScript.Shell object instead.

WScript.Shell does not have a quit method. If it did, it wouldn't help kill Firefox.

This is an example of using WMI from VBS to start, then kill a process like Firefox.

Upvotes: 1

Related Questions