O'Reilly logo

Pro Windows PowerShell by Hristo Deshev

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

22.3. FileSystemWatcher: A Real-World Example

Let's go through a complete example and put everything together. Assume we are presented with the task of monitoring a folder and notifying the user when somebody deletes a file. To do that, we use a System.IO.FileSystemWatcher object and subscribe to its Deleted event. We will do that from a script called WatchDeletedFiles.ps1:

#monitor deleted files Add-PSSnapin PSEventing -ErrorAction SilentlyContinue $fsw = New-Object System.IO.FileSystemWatcher $fsw.Path = "c:\powershell" $fsw.EnableRaisingEvents = $true Connect-EventListener fsw deleted Get-Event -wait | ' foreach { ' Write-Host -foreground Yellow ' "Warning!!! Somebody just deleted $($_.Args.FullPath)" } Disconnect-EventListener fsw deleted ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required