0

我有一个脚本可以监视文件并触发诸如更改之类的事件。它可以工作,除了我需要处理的同一个文件(之前的 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
}

`

4

0 回答 0