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
...
是否有良好的模式或更好的方式来编写它以减少代码量?
答案 0 :(得分:3)
在您的示例中,脚本块完全相同,因此在这种情况下,只需将它们放在变量中并传递它:
$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
如果您发布一个示例,其中脚本块中存在冗余,但它们不完全相同,那么将更容易显示如何最好地抽象它的示例。可能没有一个通用的解决方案。
答案 1 :(得分:-1)
您应该将重用的代码包装到函数中,请参阅此处以获取有关如何执行此操作的说明: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()