PowerShell How-To
How To Monitor a Windows Folder for New Files
- By Adam Bertram
- 05/01/2019
Events happen regularly on a typical Windows computer; files are getting moved, processes are starting and stopping, users are logging in and many more. It's important for administrators to keep tabs on some of these events, especially when those events happen around sensitive information or a mission-critical process.
One way to monitor for file events, specifically, is with a feature in Windows called event tracing. Event tracing allows administrators to subscribe to certain events happening in the background on a Windows computer and take some action on that event when it happens.
To monitor a folder for new files in Windows with PowerShell, we can use a .NET class called FileSystemWatcher. This class is in the System.IO namespace and can be created with the New-Object cmdlet.
$watcher = New-Object System.IO.FileSystemWatcher
Once you've instantiated the object, you can then provide various "parameters" to the watcher by assigning values to different object properties. For example, I'll be monitoring a folder for new files and perhaps I'd like to monitor all subfolders, as well. To do that, I'll assign the IncludeSubdirectories property.
$watcher.IncludeSubdirectories = $true
I also need to specify which folder I'll be monitoring. I do that with the Path property, and since I want the watcher to raise events when one happens, I'll also set the EnableRaisingEvents property to $true.
$watcher.Path = 'C:\FolderWhereStuffChanges'
$watcher.EnableRaisingEvents = $true
I now need to define some action to take when the event fires. For simplicity, I'll write output to the console with the name of the path of the file that gets created and the type of event. There are different types of events you can "watch," such as new files or modified files, but in this article we're just going to focus on new files.
We define this action by creating a PowerShell scriptblock. As you can see below, I'm using the built-in [$event] variable. This is a variable that will be present every time an event fires and contains information such as the file path and the type of event that fired.
$action =
{
$path = $event.SourceEventArgs.FullPath
$changetype = $event.SourceEventArgs.ChangeType
Write-Host "$path was $changetype at $(get-date)"
}
Now that I have the watcher object and the action I'd like to take when a file is created, I then need to register this event. To do that, I'll use the Register-ObjectEvent cmdlet and provide it the watcher object we created, as well as the type of action to monitor. In our case, this will be for new files.
PS> Register-ObjectEvent $watcher 'Created' -Action $action
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
23 3446d37e-b98... NotStarted False ...
Let's now drop a file into the C:\FolderWhereStuffChanges folder and see what happens.
PS C:\> $null = New-Item -path 'C:\FolderWhereStuffChanges\file.txt' -ItemType File
C:\FolderWhereStuffChanges\file.txt was Created at 03/20/2019 15:42:35
Our New-Item command didn't return anything since the output was sent to $null, but we did get a message saying the file was created. This message came from the watcher we created. This will continue to monitor this folder until the PowerShell session ends.
We can view all existing subscribed events by using the Get-EventSubscriber command. Then, to remove them, use the Unregister-Event cmdlet.
PS> Get-EventSubscriber | Unregister-Event
At this point, the subscriber has been removed and we're back to where we started.
About the Author
Adam Bertram is a 20-year veteran of IT. He's an automation engineer, blogger, consultant, freelance writer, Pluralsight course author and content marketing advisor to multiple technology companies. Adam also founded the popular TechSnips e-learning platform. He mainly focuses on DevOps, system management and automation technologies, as well as various cloud platforms mostly in the Microsoft space. He is a Microsoft Cloud and Datacenter Management MVP who absorbs knowledge from the IT field and explains it in an easy-to-understand fashion. Catch up on Adam's articles at adamtheautomator.com, connect on LinkedIn or follow him on Twitter at @adbertram or the TechSnips Twitter account @techsnips_io.