![](/img/trans.png)
[英]PowerShell script using FileSystemWatcher will not launch Python script
[英]Powershell FileSystemWatcher script firing twice on some new files
我正在使用 FileSystemWatcher 來監視文檔被掃描到的文件夾。 當檢測到新文件時,它會發送一個 email 通知某人。 它按原樣工作,但有時(不是每個文件)它會在新文件上觸發 2 或 3 次,並為同一文件發送 email 2-3 次。 我猜這與掃描儀創建文件的方式或類似的方式有關。
我試圖找出一種方法來防止這種情況發生,以確保每個文件只發送一個 email。 任何建議將不勝感激。
$PathToMonitor = "\\path\to\folder"
$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path = $PathToMonitor
$FileSystemWatcher.Filter = "*.*"
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.EnableRaisingEvents = $true
$Action = {
if ($EventArgs.Name -notlike "*.pdf" -and $EventArgs.Name -notlike "*.tif") {
return
}
$details = $event.SourceEventArgs
$Name = $details.Name
$Timestamp = $event.TimeGenerated
$text = "{0} was submitted on {1}." -f $Name, $Timestamp
$FromAddress = "Email1 <email1@email.com>"
$ToAddress = "Email2 <Email2@email.com>"
$Subject = "New File"
$SMTPserver = "123.4.5.678"
Send-MailMessage -From $FromAddress -To $ToAddress -Subject $Subject -Body $text -SmtpServer $SMTPserver
}
$handlers = . {
Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action -SourceIdentifier FSCreateConsumer
}
try {
do {
Wait-Event -Timeout 5
} while ($true)
}
finally {
Unregister-Event -SourceIdentifier FSCreateConsumer
$handlers | Remove-Job
$FileSystemWatcher.EnableRaisingEvents = $false
$FileSystemWatcher.Dispose()
}
這可能是因為您收聽了太多通知。 默認值為LastWrite
、 FileName
和DirectoryName
FileName
足以滿足您的需要,並且可能會阻止您的問題。
$FileSystemWatcher.NotifyFilter = [System.IO.NotifyFilters]::FileName
作為一個評論,我不知道你為什么使用Wait-Event -Timeout 5
。 腳本在沒有try{}
塊的情況下工作正常。
我必須調整這兩件事才能使其工作:
if ($MonitoredFiles.TryAdd($Event.SourceEventArgs.Name, $Event.TimeGenerated))
if ($OriginEventDate -ne [System.DateTime]::MinValue -and $OriginEventDate.AddMinutes($KeepFiles) -ge $Now)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.