PowerShell Monitor and Run

Sudheer Menda 1 Reputation point

How to monitor a folder for a new sub-folder created and then monitor the new subfolder for a file for a specific timeframe? When the file is detected within the timeframe, run another file in a different drive and exit. If the file is not detected within the timeframe, then exit?

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = 'Z:\abc'
$watcher.Filter ='.'
IncludeSubdirectories = $true
$watcher.Filter = 'xyz.txt'
$watcher.EnableRaisingEvents = $true

$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -action {
$path =$event.SourceEventArgs.FullPath
$changeType + $Event.SourceEventsArgs. ChangeType


JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
905 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,416 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 45,186 Reputation points

    Here's an example of using FileSystemWatcher. You can modify the code to stay in the do/while for only a certain period by 'remembering' the time you entered the loop and subtracting that from the current time after each 'sleep'. If the resulting time difference is less than the period you define, stay in the loop, otherwise use a 'break' to exit the loop.