Sajal wanted to monitor a directory, detect new file(s) and open them in their associated applications, I remember monitoring directory for changes in Linux in a Perl script. Doing something similar on Windows it seemed tough, but a after a little pondering I remembered about Windows Script Host (WSH), and after a bit of googling, coding, trial and errors, I came up with a script which does all that is required, it’s written in VBScript.
strDrive = "D:" strFolder = "\\dropbox\\downloads\\" strComputer = "." intInterval = "5" ' Connect WMI service Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\cimv2") ' build query strQuery = "Select * From __InstanceCreationEvent" _ & " Within " & intInterval _ & " Where Targetinstance Isa 'CIM_DataFile'" _ & " And TargetInstance.Drive='" & strDrive & "'"_ & " And TargetInstance.Path='" & strFolder & "'" ' Execute notification query Set colMonitoredEvents = objWMIService.ExecNotificationQuery(strQuery) ' get a shell application object Set WshShell = WScript.CreateObject("Shell.Application") Do Set objLatestEvent = colMonitoredEvents.NextEvent ' strip out the real path Response = Split(objLatestEvent.TargetInstance.PartComponent, "=") ' remove slash & quotes FileName = Replace(Response(1), """", "") FileName = Replace(FileName, "\\", "\") ' open the file in it's associated program WshShell.ShellExecute FileName, "", "", "open", 1 Wscript.Echo FileName Loop
Is this works with polling (I notify the word “interval”)? If yes then I think that polling is not good idea…
Error
Object does not support this property or method:
objLatestEvent.TargetInstance.PartComponent
Hi I need to use this script as COM component in VBA with callback support. When a new file is created then the component will call a vba callback function than handle the event in VBA.
I know how to make a COM component from VBScript but I do not know how to call a callback VBA function through VBscript COM componet
Thanks