You can monitor a specific directory in Windows 11 for new file additions using PowerShell with the System.IO.FileSystemWatcher class, Python with the watchdog library, or batch files via periodic polling. The .NET approach offers real-time event handling without constant disk reads, while Python provides cross-platform flexibility and batch scripts offer simple, dependency-free automation for basic tasks.
Real-Time Monitoring with PowerShell
PowerShell is the most robust native solution for this task because it leverages the underlying Windows API through the.NET framework. Instead of relying on inefficient polling loops that check the directory repeatedly, you can use the System.IO.FileSystemWatcher object. This method triggers events instantly when a file is created, modified, renamed, or deleted within the specified path.
To implement this, you must instantiate the watcher and define the properties. First, create the object by specifying the path to monitor. Then, set the IncludeSubdirectories property if you need to track nested folders. Finally, attach event handlers to the Created event. This ensures your script reacts immediately to changes rather than waiting for a scheduled interval.
Here is a complete example of a PowerShell script that monitors a folder and logs new files:
$path = "C:\Your\Monitor\Folder"
$filter = "*.txt"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $path
$watcher.Filter = $filter
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
$action = {
$timestamp = Get-Date
$fileName = $Event.SourceEventArgs.Name
Write-Host "New file detected: $fileName at $timestamp" -ForegroundColor Green
}
Register-ObjectEvent $watcher Created -Action $action
# Keep the script running
while ($true) { Start-Sleep -Seconds 1 }
This script registers an action that runs whenever a matching file is created. The while loop at the end keeps the PowerShell session active so it continues listening for events. If you want to stop monitoring, you can simply close the terminal or run $watcher.Dispose() in a separate console. For more advanced integration, you might look into how to run Python from Windows CMD if you prefer scripting in another language.
Monitoring with Python and Watchdog
Python is an excellent alternative, especially if you are already managing data pipelines or automation workflows. The standard library does not include a built-in directory watcher, but the community-maintainedwatchdog package provides a reliable cross-platform solution. It uses OS-specific APIs (like inotify on Linux or ReadDirectoryChangesW on Windows) to provide efficient event notifications.
First, install the library using pip:
pip install watchdog
Next, create a Python script that inherits from FileSystemEventHandler. You must override the on_created method to define what happens when a new file appears. This approach is highly modular and allows you to easily extend functionality, such as moving files or sending email notifications.
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory:
print(f"File created: {event.src_path}")
if __name__ == "__main__":
path = "C:\\Your\\Monitor\\Folder"
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
This script starts an observer thread that listens to the specified path. When a file is created, the handler prints the full path. The try-except block ensures a clean shutdown when you press Ctrl+C. This method is particularly useful if you need to process files asynchronously or integrate with other Python libraries.
Batch File Polling Method
If you cannot install external libraries or run PowerShell scripts due to security policies, a batch file using a polling loop is the fallback option. This method checks the directory at fixed intervals, comparing the current state against a stored list of files. While less efficient than event-driven approaches, it requires no additional software. You can use thedir command to list files and compare them with a previous snapshot. However, maintaining a consistent state in pure batch scripting is complex. A simpler approach is to use forfiles to find files modified within the last minute. This command searches for files with a modification time greater than a specified offset.
@echo off
setlocal enabledelayedexpansion
:loop
forfiles /p "C:\Your\Monitor\Folder" /m *.txt /d 0 /c "cmd /c echo New file found: @file"
timeout /t 5 /nobreak >nul
goto loop
The /d 0 parameter selects files modified today. The timeout command adds a delay between checks. Note that this method may miss very fast file creation and deletion cycles, and it generates more disk I/O than the PowerShell or Python methods. For sorting issues related to batch commands, see how to sort files by time in a batch file.
Choosing the Right Tool
Selecting the appropriate monitoring tool depends on your environment constraints and performance requirements. PowerShell is ideal for system administrators who need native, high-performance monitoring without installing third-party packages. It integrates seamlessly with Windows Event Logs and other system tools. Python is best for developers who need complex logic, such as parsing file contents or integrating with web services. Its rich ecosystem makes it easier to handle edge cases like file locking or encoding issues. Batch files are suitable only for simple, low-frequency checks where ease of deployment outweighs the need for precision. Always test your chosen method in a staging environment to ensure it handles concurrent file operations correctly.Frequently Asked Questions
Can I monitor network drives with these methods?
Yes, all three methods support network paths, but performance may vary. PowerShell's FileSystemWatcher works reliably over SMB shares, though latency might cause slight delays. Python's watchdog also supports UNC paths, but network interruptions can sometimes trigger false change events. Batch polling over networks is generally slower and more prone to timeout errors.
How do I exclude certain file types from monitoring?
In PowerShell, modify the $watcher.Filter property to specify patterns like *.txt or use regex logic inside the event action. In Python, add an if statement inside the on_created method to check the file extension before processing. Batch files can use the /m switch in forfiles to limit results to specific extensions.
What happens if the monitored folder is deleted?
If the root folder is deleted, the FileSystemWatcher will throw an exception or stop raising events until you recreate the directory and reinitialize the watcher. In Python, the observer will continue running but may fail to detect new files until the path exists again. Always wrap your monitoring code in error-handling blocks to restart the watcher automatically if the path becomes invalid.
Is there a way to monitor multiple directories at once?
Yes, you can create multiple instances of the watcher object. In PowerShell, instantiate separate FileSystemWatcher objects for each path and register distinct actions or use a shared action with path checking. In Python, schedule the same or different handlers to multiple paths using separate Observer instances or one observer with multiple schedule calls.
Why is my PowerShell script consuming high CPU?
High CPU usage usually indicates a polling loop instead of event-based monitoring. Ensure you are using Register-ObjectEvent and not a while loop with Get-ChildItem. If you must poll, increase the Start-Sleep duration. Also, check if your event action contains heavy processing that blocks the main thread, causing retries or delays.