1. 复制下面代码到txt文件中
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "D:source"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$logline = "$(Get-Date), $changeType, $path"
Add-content "D:log.txt" -value $logline
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
Register-ObjectEvent $watcher "Deleted" -Action $action
Register-ObjectEvent $watcher "Renamed" -Action $action
while ($true) {sleep 5}
2. 配置以下双引号内的参数
1. 监控文件夹:$watcher.Path = "D:source"
2. 监控文件类型,可以log文件*.log,或者所有文件*.*:$watcher.Filter = "*.*"
3. 监控子文件夹: $watcher.IncludeSubdirectories = $true
4. 日志文件位置:Add-content "D:log.txt" -value $logline
3. 另存为StartMonitoring.ps1, 右击 使用powershell运行
4. 在日志文件位置会生成log.txt,里面存放所有监控文件夹内的文件变动情况,包含文件的 创建,改变,删除,重命名。
来源windows - How to monitor a folder and trigger a command-line action when a file is created or edited? - Super User



