A simple script that create a file watcher on a specific folder and collect the events in a global variable.
function watch-folder {
param([string]$path)
$fileSystemWatcher = new-object System.IO.FileSystemWatcher
$fileSystemWatcher.Path = $path
$global:events = new-object system.data.datatable
[void] $events.Columns.Add("Time", [datetime])
[void] $events.Columns.Add("Full path", [string])
[void] $events.Columns.Add("Change type", [string])
$event = {
[void] $events.Rows.Add([datetime]::Now, $eventArgs.FullPath, $eventArgs.ChangeType)
}
[void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Created -Action $event)
[void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Changed -Action $event)
[void](Register-ObjectEvent -InputObject $fileSystemWatcher -EventName Deleted -Action $event)
}
cls
watch-folder "c:\Temp"
"foobar" > c:\temp\test.txt
del c:\temp\test.txt
$global:events
get-eventsubscriber -force | unregister-event -force
I get this when I run this script:
ReplyDeleteUnexpected token 'Register-ObjectEvent' in expression or statement.
At C:\users\administrator\Documents\scripts\Watchfolder.ps1:17 char:32
+ [void] Register-ObjectEvent <<<< -InputObject $fsw -EventName Created -Action $a
ction
+ CategoryInfo : ParserError: (Register-ObjectEvent:String) [], ParseExce
ption
+ FullyQualifiedErrorId : UnexpectedToken
I have three different files in different subfolders & I want it to check every 5 minutes for any changes to those files.
ReplyDeleteI have it watching the main folder but it doesn't seem to do anything after changes are made.
Well, I forgot to mention that it should start another another .ps1; when a change has been made.
ReplyDelete