使用FileSystemWatcher监视目录 [英] Monitor a directory with FileSystemWatcher
问题描述
我有一个正在被某些程序填充的目录.我想监视此目录,并检查文件是否不断添加到该目录中.如果例如5分钟,没有文件被添加到目录,我想得到通知.文件也将被删除,但我只需要关心新文件.
该脚本每三个小时运行大约20分钟.
FileSystemWatcher的代码:
I have a directory which is getting filled by some program. I would like to monitor this directory and check if files are continuously getting added to the directory. If for Example for 5 min no file is getting added to the direcotry I want to get notified. The Files are also getting deleted but i just have to care about the new files.
The script would run for about 20 min every three hours.
The code for the FileSystemWatcher:
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\temp\test"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$created = Register-ObjectEvent $watcher "Created" -Action {
write-host "Created: $($eventArgs.FullPath)"
Get-Date -Format "HH:mm:ss" | Out-File "C:\temp\log.txt" -Append
}
我不知道该如何做到这一点,我很感谢每一次的投入.
I don't know how i could achive this, and I'm thankful for every input.
推荐答案
PowerShell脚本不太适合连续运行并报告事件.
PowerShell scripts are not well suited to run continuously and report on events.
一种实现所需目标的方法是使用如下脚本:
One way to achieve what you want is using a script like this:
[DateTime] $LastWriteTime = (Get-ChildItem -Path "C:\temp\test" -File | Sort-Object LastWriteTime | Select -Last 1).LastWriteTime
if ($LastWriteTime -le (Get-Date).AddMinutes(-5))
{
Write-Output "No files added in the last 5 minutes"
# notify me...
}
并安排Windows Task Scheduler中的脚本每五分钟运行一次.
and schedule the script in Windows Task Scheduler to run every five minutes.
它将找到目录中编辑的最新文件.
It finds the newest file edited in the directory.
不需要FileSystemWatcher
No need for a FileSystemWatcher
这篇关于使用FileSystemWatcher监视目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!