Powershell 新手。我正在编写一个脚本来监视目录中的文件并将更改报告给控制台。
我注意到我用于 FS“观察者”的脚本块中有相当多的代码重复。
这是脚本块的片段。如果需要,我可以发布整个脚本,它会更长一点,还有更多内容。
# 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
...
有没有更好的模式或更好的编写方式来减少代码量?