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]

Do not forget to share if you like:
Pradeep

Recent Posts

Self-hosting free password manager : Vaultwarden

Bitwarden is an open-source password manager that helps individuals and organizations securely store, manage, and…

9 months ago

Get Started with IPTV: Free and Paid Options for All Devices

In today's digital age, traditional cable TV is steadily being replaced by more flexible and…

11 months ago

Installing Log2RAM utility on your Raspberry Pi

log2ram is a utility specifically designed for Linux-based systems, particularly single-board computers like the Raspberry…

11 months ago

ChatGPT Voice Shortcut on iOS, Android

How to Add a ChatGPT Voice Shortcut on iOS and Android With voice commands and…

11 months ago

Proxy Through SSH Tunnel

For occasional VPN or proxy, you do not always need to pay for a reliable…

1 year ago

Unlocking the Power of Time Machine: The Easiest Way to Back Up Your Mac

When it comes to protecting your Mac, Time Machine offers an effortless and powerful way to keep…

1 year ago