The code runs with no errors, however when I add/delete a file in the filesystem, the code does not perform the action it should in Register-ObjectEvent $watcher "watchType" -Action $action
. I know this because in the past, it was working and would create/add to log.txt
a record of the file deleted/added and its date. Now, nothing happens. What is going on?
Code:
#local path of the folder you want to sync. By default sets to current directory
$localPath = get-location
#filter specific files by name/type
$filter = "*.*"
#include subdirectories
$inclSubDirectories = $true
#end of user defined variables
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $localPath
$watcher.Filter = $filter
$watcher.IncludeSubdirectories = $inclSubDirectories
$watcher.EnableRaisingEvents = $true
$oldContent = ""
$action = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "'$localPath'\log.txt" -value $logline
}
$created = Register-ObjectEvent $watcher "Created" -Action $action
$action1 = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "'$localPath'\log.txt" -value $logline
}
$deleted = Register-ObjectEvent $watcher "Deleted" -Action $action1
$exitAction = {
"File wathcer unregistered!"
Unregister-Event $created
Unregister-Event $deleted
}
$exit = Register-EngineEvent PowerShell.Exiting -action $exitAction
while ($true) {
if($oldContent -eq $logline){}
else{
$logline
$oldContent = $logline
}
Start-Sleep -m 1000
}
EDIT
I decided to try to copy and paste the code directly into PowerShell, and it works the way it should... Not entirely, it doesn't output but it does update log.txt like how it should. Actually, it only worked once. Now it's back to what it was like before.
EDIT v2
It seems to work only once per event (create, then delete) when I copy-paste into the PowerShell (for instance, it would register a file deleted in log, then it would register a file created, but it wouldn't do anything else.) It is still not outputting like it should.
I could see here for your $localpath
is having the Current path and the problem comes when you do Add-Content
.
In below line, The path comes with singelqoutes in it, which is not existing any way.
Add-content "'$localPath'\log.txt" -value $logline
See it by just printing "'$localPath'\log.txt"
.
Correct Expression would be Add-content "$localPath\log.txt" -value $logline
As well as on each Register-ObjectEvent
execution, a job will be created,try
Receive-Job -Id <Job ID> -keep
to see what is happening/happened.
Regards
kvprasoon