# make sure the watcher emits events $FileSystemWatcher.EnableRaisingEvents = $true
# define the code that should execute when a file change is detected $Action = { $details = $event.SourceEventArgs $Name = $details.Name $FullPath = $details.FullPath $OldFullPath = $details.OldFullPath $OldName = $details.OldName $ChangeType = $details.ChangeType $Timestamp = $event.TimeGenerated $text = "{0} was {1} at {2}"-f$FullPath, $ChangeType, $Timestamp Write-Host"" Write-Host$text-ForegroundColor Green
# you can also execute code based on change type here switch ($ChangeType) { 'Changed' { "CHANGE" } 'Created' { "CREATED"} 'Deleted' { "DELETED" # uncomment the below to mimick a time intensive handler <# Write-Host "Deletion Handler Start" -ForegroundColor Gray Start-Sleep -Seconds 4 Write-Host "Deletion Handler End" -ForegroundColor Gray #> } 'Renamed' { # this executes only when a file was renamed $text = "File {0} was renamed to {1}"-f$OldName, $Name Write-Host$text-ForegroundColor Yellow } default { Write-Host$_-ForegroundColor Red -BackgroundColor White } } }