我有一个脚本可以监视文件并触发事件,例如更改。除了为同一个文件(我之前的Stackflow问题)触发了重复事件,我需要处理它。我正在将文件名写入日志文件,只有在不存在时才重新记录它。
问题是我认为事件是同步触发的,即使我正在检查重复,我在日志中获得2个条目以进行1个文件更改。我不知道如何解决这个问题。
以下是代码:
Unregister-Event FW*
$source = 'S:\FIS-BIC Reporting\Report Output Files\IT\'
$filter = '*.*'
$MasterFile = "H:\PS\EmailNotifications.csv"
$LogFile = "H:\EmailNotify.log"
$FilesToCheck = import-csv -path $Masterfile
if (! (Test-Path $Logfile))
{
$Output = "Date|Filename|FilenameSpec|Email"
$Output | Out-File $LogFile
}
function Get-CharRight($str,$chars)
{
return $str.Substring($str.Length – $chars, $chars)
}
function ProcessFile()
{
param ([string]$filename)
Write-Host "file: $filename"
$ext= (Get-CharRight $filename 3)
if ($ext -ne "tmp")
{
foreach($FileToCheck in $FilesToCheck)
{
if($filename -like $FileToCheck.FilenameSpec)
{
Write-Host "Match"
#check log to see if an email was already sent
$Exists = import-csv -path $Logfile -delimiter "|" | where-object {$_.Filename -eq $filename}
Write-Host ($Exists.Count -eq $null)
if ($Exists.Count -eq $null)
{
Write-Host "Not in logfile"
$Date = Get-Date -format G
$Output = $Date + "|" + $filename + "|" + $FileToCheck.FilenameSpec + "|" + $FileToCheck.Email
$Output | Out-File $LogFile -append
}
else
{write-host "duplicate"}
}
}
}
}
$fsw = New-Object IO.FileSystemWatcher $source, $filter -Property @{IncludeSubdirectories = $true; NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite, Attributes'}
Register-ObjectEvent $fsw Changed -SourceIdentifier FWFileChanged -Action {
ProcessFile $Event.SourceEventArgs.FullPath
}
Register-ObjectEvent $fsw Created -SourceIdentifier FWFileCreated -Action {
ProcessFile $Event.SourceEventArgs.FullPath
}
while($true) {
start-sleep -s 2
}
`