Monitor a directory with FileSystemWatcher

2019-06-10 20:04发布

问题:

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.

回答1:

You could have a separate script running via Task Scheduler which uses your log file to see if a file has been created in the last 5 minutes.

$log = Get-Content -Path T:\log.txt 
$currentTime = Get-date
$5minutesAgo = $currentTime.AddMinutes(-5)
$FileAdded = $false

foreach($time in $log){
    if((get-date $time) -gt $5minutesAgo){
        $FileAdded = $true
    }
}

If($FileAdded) {
    Write-host "File was added in the last 5mins"
} Else {
    Write-host "No file added in the last 5mins"
    # Add in email code here
}

This will go through your log file line by line and check if the time was within the last file minutes. Then it will set the variable $FileAdded to $true if there was a file added. You can then use this to decide if an email should be send or not.

Note: If this is being run constantly make sure you roll over your log files regular to keep the processing down. As you are not including a the date in your log file you would have to roll over your log file at least once a day.



回答2:

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...
} 

and schedule the script in Windows Task Scheduler to run every five minutes.

It finds the newest file edited in the directory.

No need for a FileSystemWatcher