Quick Links
Files are in a constant state of flux on any operating system.
Enter the .NETFileSystemWatcher classand PowerShell.
In .NET and .NET Core, FileSystemWatcher is a class that lives in the System.IO namespace and monitors files.
In PowerShell, this can be very useful, especially when it’s combined with other PowerShell functions.
Instantiating the FileSystemWatcher
Instantiate this class in PowerShell by running
.
Once you do, you’ll need to tell it which folder to watch.
Do this by running
.
To get started, you’re gonna wanna define an action block in the code.
Right now, these two are separate and don’t know about each other.
To get them working together, you must register the actions with the event.
PowerShell has an entire cmdlet for this—theRegister-ObjectEventcmdlet.
Testing It Out
Now you’re able to test it all out.
To create a new file and trigger the event, fire off the below line in PowerShell.
As soon as you enter that, the event fires and the action triggers.
The file should be created, but no event shows.
Now even if the EnableRaisingEvents flag is true and the action happens, the action won’t fire.