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
...
是否有一种好的模式或更好的方法来编写以减少代码量?
在您的示例中,脚本块完全相同,因此在这种情况下,只需将它们放入变量中并传递即可:
$action = {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
$console_message = "The file '$name' was '$changeType' at '$timeStamp'"
Write-Host message
}
# File creation
Register-ObjectEvent $watcher Created -SourceIdentifier Created -Action $action
# File change
Register-ObjectEvent $watcher Changed -SourceIdentifier Changed -Action $action
如果您发布一个示例,其中脚本块中存在冗余,但它们并不完全相同,那么展示如何最好地抽象它的示例会更容易。可能没有一个放之四海而皆准的解决方案。
您应该将重用的代码包装到函数中,有关如何执行此操作的说明,请参阅此处: http://windowsitpro.com/windows/create-your-own-powershell-functions
在您的情况下,我将创建以下函数:
function FileChange {
Register-ObjectEvent $watcher Created -SourceIdentifier Created -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
$console_message = "The file '$name' was '$changeType' at '$timeStamp'"
Write-Host message
}
然后使用它来替换重复的代码:
# Filter all files
$filter = "*.*"
$watcher = New-Object IO.FileSystemWatcher $watchdir, $filter -Property @{
IncludeSubdirectories = $true
EnableRaisingEvents = $true
}
# File creation
FileChange()
# File change
FileChange()