Reputation: 746
I want to create a script which will run a sound when a new file is added to a folder. The problem is that I had opened the vbscript at least 5 times to test the code and the code runs 5 times when I add only 1 file. It looks like multiple instances of the script are running at the same time.
How to restore the script? EDIT: I've found a temporary fix, which is to restart the WMI services using net stop winmgmt net start winmgmt But this is not practical since I would have to restart the WMI every time to test a vbscript using WMI.
Dim objShell
Set objShell = Wscript.CreateObject("WScript.Shell")
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
& "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=""c:\\\\scripts""'")
Do
Set objLatestEvent = colMonitoredEvents.NextEvent
objShell.Run "Soundscript.vbs"
' Using Set is mandatory
Set objShell = Nothing
Set objWMIService = Nothing
Loop
Upvotes: 0
Views: 913
Reputation: 1474
Test your script using cscript.exe by right clicking it as shown below. Double clicking to run the script would default to using wscript.exe which runs in the background.
The code below shouldn't be added. It will dispose of the WMI object that is bound to the event listener, exiting the loop and the script.
Set objWMIService = Nothing
Upvotes: 0
Reputation: 8572
You have an infinite loop, which is fine if intentional but means that for testing you will always have to kill the process (because there is no condition which causes it to exit on its own). If you are double-clicking the script to test it, you'll have to kill the wscript.exe process to terminate the script; alternatively for testing it may be easier to open a command prompt and run the script via cscript, e.g. cscript C:\scripts\myscript.vbs
which will allow you to kill the script when you want by sending Ctrl+C to the command prompt.
And now I will contradict myself because there is something in your script that will cause it to exit, namely the fact that you're destroying the objShell
object in the loop but using it again in the next iteration. That will result in a runtime error on the second iteration, causing your script to terminate (since error handling isn't enabled). You can quite happily remove both of your Set x = Nothing
statements from your loop.
Upvotes: 2