Использование FileSystemWatcher для предупреждения, если несколько файлов изменяются одновременно - PullRequest
0 голосов
/ 08 февраля 2019

Я очень новичок в powershell.Следующий код создан BigTeddy, и он получает полную оценку (я также внес некоторые изменения, используя цикл while)

Я хочу знать, как я могу создать оператор if / else так, чтобы, если большечем один файл был изменен / отредактирован / создан / удален одновременно (скажем, десять файлов были отредактированы одновременно) будет создан файл журнала о том, что эти файлы списка были отредактированы одновременно в это конкретное время.

Следующий скрипт PowerShell, созданный BigTeddy, в основном выплевывает файл журнала (и на выходе ISE PowerShell) о том, когда было выполнено изменение / редактирование / создание / удаление, когда оно было изменено и какие файлы былиотредактировано.

 param(
        [string]$folderToWatch = "C:\Users\gordon\Desktop\powershellStart"
      , [string]$filter        = "*.*"
      , [string]$logFile       = 'C:\Users\gordon\Desktop\powershellDest\filewatcher.log'
    )

    # In the following line, you can change 'IncludeSubdirectories to $true if required.
    $fsw = New-Object IO.FileSystemWatcher $folderToWatch, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
    $timeStamp           #My changes
    $timeStampPrev = $timeStamp         #My changes
# This script block is used/called by all 3 events and:
# appends the event to a log file, as well as reporting the event back to the console
$scriptBlock = {

  # REPLACE THIS SECTION WITH YOUR PROCESSING CODE
  $logFile = $event.MessageData # message data is how we pass in an argument to the event script block
  $name = $Event.SourceEventArgs.Name
  $changeType = $Event.SourceEventArgs.ChangeType
  $timeStamp = $Event.TimeGenerated
  while($timeStampPrev -eq $timeStamp) {     #My changes
  Write-Host "$timeStamp|$changeType|'$name'" -fore green
  Out-File -FilePath $logFile -Append -InputObject "$timeStamp|$changeType|'$name'"
  # REPLACE THIS SECTION WITH YOUR PROCESSING CODE
}
}


# Here, all three events are registered.  You need only subscribe to events that you need:
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -MessageData $logFile -Action $scriptBlock
Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -MessageData $logFile -Action $scriptBlock
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -MessageData $logFile -Action $scriptBlock

# To stop the monitoring, run the following commands:
#  Unregister-Event FileDeleted  ;  Unregister-Event FileCreated  ;  Unregister-Event FileChanged


#This script uses the .NET FileSystemWatcher class to monitor file events in folder(s).
#The advantage of this method over using WMI eventing is that this can monitor sub-folders.
#The -Action parameter can contain any valid Powershell commands.
#The script can be set to a wildcard filter, and IncludeSubdirectories can be changed to $true.
#You need not subscribe to all three types of event.  All three are shown for example.

1 Ответ

0 голосов
/ 13 февраля 2019

Рассматривали ли вы хеш-таблицу с метками времени и действием (создание / изменение / удаление) в качестве ключей, а имя файла - в качестве значения.После определенного интервала ожидания вы выполняете итерацию по словарю и сбрасываете записи в словаре в файл журнала.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...