PowerShell Monitor and Run

Sudheer Menda 1 Reputation point
2021-08-02T15:32:22.277+00:00

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

...STUCK HERE

JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
942 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,463 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 45,906 Reputation points
    2021-08-02T18:35:07.323+00:00

    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.

    using-filesystemwatcher-correctly-part-2