New to Powershell. I am writing a script that watches files in a directory and reports the changes to the console.
I am noticing quite a bit of code duplication in the script blocks I'm using for the FS "watchers".
Here is a snippet of the script blocks. I can post the whole script if needed, it's a little longer and there's a little more going on.
# Filter all files
$filter = "*.*"
$watcher = New-Object IO.FileSystemWatcher $watchdir, $filter -Property @{
IncludeSubdirectories = $true
EnableRaisingEvents = $true
}
# File creation
Register-ObjectEvent $watcher Created -SourceIdentifier Created -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
$message = "The file '$name' was '$changeType' at '$timeStamp'"
Write-Host $message
}
# File change
Register-ObjectEvent $watcher Changed -SourceIdentifier Changed -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
$message = "The file '$name' was '$changeType' at '$timeStamp'"
Write-Host $message
}
# File rename
...
# File delete
...
Is there a good pattern or nicer way of writing this to reduce the amount of code?