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 ...

Get Pro Windows PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.