I am trying to create a systemFileWatcher that watches a specific excel file for any changes. When triggered it should runs a few commands, logs the activity and then continues watching. However, for now I am unable to get the watcher to react to changes in the .xlsx file. My watcher is currently set up as follows, based an answer here.
$watch_path = 'D:\Projects\test\'
$watch_file = 'test.xlsx'
SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $watch_path
$watcher.Filter = $watch_file
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "log.txt" -value $logline
}
DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
while ($true) {sleep 60}
This does not trigger on a save within the excel program, however when I put the default filter of '.' it reacts to the temporary files created with this saving. I don't want that though, as there are more files in this folder that the watcher should not react to. How do I fix this filter/watcher?
EDIT:
I just wanted to add some output to this question. Adding the line: Write-Host $logline after creating $logline I get the following ouput:
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
1 7dd34e5a-484... NotStarted False $path = $Event.Source...
2 d7a74a71-5ae... NotStarted False $path = $Event.Source...
Then I open the Excel File:
03/12/2024 11:34:39, Created, D:\Projects\test\~$test.xlsx
03/12/2024 11:34:40, Changed, D:\Projects\test\~$test.xlsx
Then I change and save the Excel file:
03/12/2024 11:35:06, Created, D:\Projects\test\845C7B30
03/12/2024 11:35:06, Changed, D:\Projects\test\845C7B30
03/12/2024 11:35:06, Changed, D:\Projects\test\845C7B30
Finally I close the excel file, but I get no further messages.