powershell - 使用 FileSystemWatcher 在多个文件同时更改时发出警报
问题描述
我对powershell很陌生。以下代码由 BigTeddy 创建,他获得了全部功劳(我还使用 While 循环进行了一些更改)
我想知道如何创建一个 if/else 语句,以便如果同时更改/编辑/创建/删除多个文件(例如同时编辑了十个文件),将创建一个日志文件,说明这些列表文件已在此特定时间同时进行了编辑。
BigTeddy 创建的以下 powershell 脚本基本上会吐出一个日志文件(以及在 powershell ISE 的输出上),其中包含进行更改/编辑/创建/删除的时间、更改时间以及编辑了哪些文件。
param(
[string]$folderToWatch = "C:\Users\gordon\Desktop\powershellStart"
, [string]$filter = "*.*"
, [string]$logFile = 'C:\Users\gordon\Desktop\powershellDest\filewatcher.log'
)
# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher $folderToWatch, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
$timeStamp #My changes
$timeStampPrev = $timeStamp #My changes
# This script block is used/called by all 3 events and:
# appends the event to a log file, as well as reporting the event back to the console
$scriptBlock = {
# REPLACE THIS SECTION WITH YOUR PROCESSING CODE
$logFile = $event.MessageData # message data is how we pass in an argument to the event script block
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
while($timeStampPrev -eq $timeStamp) { #My changes
Write-Host "$timeStamp|$changeType|'$name'" -fore green
Out-File -FilePath $logFile -Append -InputObject "$timeStamp|$changeType|'$name'"
# REPLACE THIS SECTION WITH YOUR PROCESSING CODE
}
}
# Here, all three events are registered. You need only subscribe to events that you need:
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -MessageData $logFile -Action $scriptBlock
Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -MessageData $logFile -Action $scriptBlock
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -MessageData $logFile -Action $scriptBlock
# To stop the monitoring, run the following commands:
# Unregister-Event FileDeleted ; Unregister-Event FileCreated ; Unregister-Event FileChanged
#This script uses the .NET FileSystemWatcher class to monitor file events in folder(s).
#The advantage of this method over using WMI eventing is that this can monitor sub-folders.
#The -Action parameter can contain any valid Powershell commands.
#The script can be set to a wildcard filter, and IncludeSubdirectories can be changed to $true.
#You need not subscribe to all three types of event. All three are shown for example.
解决方案
您是否考虑过以时间戳和操作(创建/修改/删除)作为键、文件名作为值的哈希表。您在特定的等待间隔后遍历字典,并将字典中的条目刷新到日志文件中。
推荐阅读
- asp.net-mvc - 相同 EF 模型(数据库)的不同数据库上下文?
- rust - 如何延长结构的生命周期,以便可以使用它调用 tokio::run?
- javascript - 在 Javascript 中计算百分比。
- java - 从控制器调用时出现 java.lang.NullPointerException
- javascript - 独立于页面缩放级别和 Windows 缩放设置检测屏幕分辨率
- angular - 如何在 Angular 7 中正确使用 compareWith 和响应式表单?
- css - 在 kendo-ui 中忽略了 angular 的字体设置
- android - Android Studio 服务无法启动
- java - Java序列化可以将对象反序列化为父类的实例吗
- unity3d - 带有滚动条的增长菜单