Powershell FileSystemWatcher мониторинг нескольких папок - PullRequest
0 голосов
/ 17 июня 2020

У меня есть код для отслеживания нескольких папок и отображения всплывающего сообщения (+ добавить файл журнала), но он не работает, и я не могу понять почему (извините, я новичок в PS, и код был состоит из частей кода, которые можно найти в Интернете). У меня есть две папки для просмотра, но сначала сценарий заботится только об изменениях в первой папке в "elenco_cartelle.txt". Затем, когда изменение зарегистрировано, PS запускает бесконечный l oop с данными об изменении, но отображает всплывающее окно и обновляет файл журнала. Я также попытался переместить «$ i = $ i + 1» из строки кода, которая должна быть, но эти две проблемы все еще остаются. Любая помощь для новичка ie? Спасибо.

Вот код:

$i=0
   $LogFile = "c:\Users\Laura\Desktop\Logga.txt"
   $PathToMonitor = Get-Content "C:\Users\Laura\Documents\elenco_cartelle.txt";
   foreach ($path in $PathToMonitor)  
   { 
   explorer $PathToMonitor
   $FileSystemWatcher = New-Object System.IO.FileSystemWatcher $path -Property @{IncludeSubdirectories = 
   $true}
   Add-Type -AssemblyName System.Windows.Forms
   $FileSystemWatcher.EnableRaisingEvents = $true

   Register-ObjectEvent $FileSystemWatcher Changed -SourceIdentifier "$i+folderChanged" -Action { 

    $details = $event.SourceEventArgs
    $Name = $details.Name
    $FullPath = $details.FullPath
    $OldFullPath = $details.OldFullPath
    $OldName = $details.OldName
    $ChangeType = $details.ChangeType
    $Timestamp = $event.TimeGenerated
    $text = "{0} was {1} at {2}" -f $FullPath, $ChangeType, $Timestamp
    $text1 = "{0} è stato inserito per la firma" -f $FullPath

    [System.Windows.Forms.MessageBox]::Show("$text1","Avviso di disponibilità di file",`
    [System.Windows.Forms.MessageBoxButtons]::OK,`
    [System.Windows.Forms.MessageBoxIcon]::Information,`
    [System.Windows.Forms.MessageBoxDefaultButton]::Button1,`
    [System.Windows.Forms.MessageBoxOptions]::ServiceNotification)


    Add-Content c:\users\Laura\Desktop\test.txt $text


    Write-Host ""
    Write-Host $text -ForegroundColor Green

        default { Write-Host $_ -ForegroundColor Red -BackgroundColor White }

   }

   $handlers = . {
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Changed -Action $Action - 
    SourceIdentifier FSChange
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action - 
    SourceIdentifier FSCreate
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Deleted -Action $Action - 
    SourceIdentifier FSDelete
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Renamed -Action $Action - 
    SourceIdentifier FSRename
   }

   Write-Host "Watching for changes to $PathToMonitor"

   try
   {
    do
    {
        Wait-Event -Timeout 1
        Write-Host "." -NoNewline

    } while ($true)

   $i=$i+1 
   }
   finally
   {
    # this gets executed when user presses CTRL+C
    # remove the event handlers
    Unregister-Event -SourceIdentifier FSChange
    Unregister-Event -SourceIdentifier FSCreate
    Unregister-Event -SourceIdentifier FSDelete
    Unregister-Event -SourceIdentifier FSRename
    # remove background jobs
    $handlers | Remove-Job
    # remove filesystemwatcher
    $FileSystemWatcher.EnableRaisingEvents = $false
    $FileSystemWatcher.Dispose()
    "Event Handler disabled."
   } 
   }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...