Categories: Tips & Tricks

Monitor Directory For New Files With WSH

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.

[vb]
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
[/vb]

Pradeep

Share
Published by
Pradeep

Recent Posts

Update Google AMP Cache with Perl

While implementing Google AMP (Accelerated Mobile Pages) for your website, it might occur to you…

6 years ago

Don’t buy Reliance Jio’s JioFi Device or JioPhone – Avoid at all cost

Thinking of buying the JioFi device by reliance or to be precise any device by…

7 years ago

Solution for Copy Paste or right click disabled in Websites Chrome

Do you hate those pesky javascripts. Majority of the banking, utility bill payment etc so…

10 years ago

Sync personal ebooks with notes, bookmarks reading position on your Kindle

So amazon has this amazing feature called whispersync : If you read the same Kindle…

11 years ago

Google Authenticator: Moving To A New Phone

Getting a new HTC One left me wondering how will I move Google Authenticator from…

11 years ago

Electronic Arts Free Games! Free ITunes Gift Vouchers

Get Bad Company 2, ME: Infiltrator, etc for free Free Games you can get today:…

12 years ago