Tuesday, June 11, 2019

Monitor Changes in a Folder

I receive a daily email from Powershell.com (www.powershell.com).  When I saw this script I said to myself, "There were times I really could have used this.".  Particularly when I wanted to know what files were affected when running an update.  I saved this file as Run-fileWatcher.ps1:


In this example, I created a folder called Test_Folder


# Change the $folder variable to the folder you want to monitor
$folder = "C:\Test_Folder"
$filter = '*'  # looks for all changes


 try
{
   $fsw = New-Object System.IO.FileSystemWatcher $folder , $filter -ErrorAction Stop # the FileSystemWatcher component watches for changes in the LastWrite and LastAccess properties of a file.
}


catch [System.ArgumentException] # checks for errors
{
   Write-Warning "Oops: $_"
   return
}

$fsw.IncludeSubdirectories = $true
$fsw.NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'

do
{
   $result = $fsw.WaitForChanged([ System.IO.WatcherChangeTypes]::All, 1000)
   if ($result.TimedOut) { continue }
 
   $result


   Write-Host "Change in $($result.Name) - $( $result.ChangeType)"

} while ($true)


While the script was running, I created a file called Test.txt.  Inside the file, I entered "This is a test."  I saved the file to c:\test_folder, and the output was:



When I deleted the file, the output was:



It should be possible to write the output to a file, but I haven't tested that yet.  I will put that on my list, as well as adding modification time and date.


I hope you found this helpful.  Again, go to www.powershell.com and sign up for their email.  Some of their scripts I use regularly.


Later,
Mike E



No comments:

Post a Comment