laola89

Untitled

Jun 13th, 2020
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Clear-Host
  2. $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
  3.  
  4.  
  5. $fileSystemWatcherDirPath = 'C:\temp'
  6. $fileSystemWatcherFilter = '*.*'
  7.  
  8. $fileSystemWatcher = [System.IO.FileSystemWatcher]::new($fileSystemWatcherDirPath , $fileSystemWatcherFilter)
  9. $fileSystemWatcher.IncludeSubdirectories = $true
  10. $fileSystemWatcher.EnableRaisingEvents = $true
  11. $fileSystemWatcher.NotifyFilter = [System.IO.NotifyFilters]::FileName -bor [System.IO.NotifyFilters]::DirectoryName -bor [System.IO.NotifyFilters]::LastWrite  # [System.Linq.Enumerable]::Sum([System.IO.NotifyFilters].GetEnumValues())
  12.  
  13. # Create syncronized hashtable
  14. $syncdFsItemEventHashT = [hashtable]::Synchronized([hashtable]::new())
  15.  
  16. $fileSystemWatcherAction = {
  17.     try {
  18.         $fsItemEvent = [pscustomobject]@{
  19.             EventIdentifier  = $Event.EventIdentifier
  20.             SourceIdentifier = $Event.SourceIdentifier
  21.             TimeStamp        = $Event.TimeGenerated
  22.             FullPath         = $Event.SourceEventArgs.FullPath
  23.             ChangeType       = $Event.SourceEventArgs.ChangeType
  24.         }
  25.  
  26.         # Collecting event in synchronized hashtable (overrides existing keys so that only the latest event details are available)
  27.         $syncdFsItemEventHashT[$fsItemEvent.FullPath] = $fsItemEvent
  28.     } catch {
  29.         Write-Host ($_ | Format-List * | Out-String ) -ForegroundColor red
  30.     }
  31. }
  32.  
  33.  
  34. # Script block which processes collected events and do further actions like copying for backup, etc...
  35. # That scriptblock was initially used to test "Start-Job". Unfortunately it's not possible to access and modify the synchronized hashtable created within this scope.
  36. $fSItemEventProcessingJob = {
  37.     $keys = $syncdFsItemEventHashT.psbase.Keys
  38.  
  39.     foreach ($key in $keys) {
  40.         $fsEvent = $syncdFsItemEventHashT[$key]
  41.  
  42.         try {
  43.             if ($fsEvent.ChangeType -eq [System.IO.WatcherChangeTypes]::Deleted) {
  44.                 $syncdFsItemEventHashT.Remove($key )
  45.                 Write-Host ("==> Item '$key' with changetype '$($fsEvent.ChangeType)' removed from hashtable without any further actions!") -ForegroundColor Blue
  46.                 continue
  47.             }
  48.  
  49.             # get filesystem object
  50.             $fsItem = Get-Item -LiteralPath $fsEvent.FullPath
  51.  
  52.             if ($fsItem -is [System.IO.FileInfo]) {
  53.                 # file processing
  54.  
  55.                 try {
  56.                     # Check whether the file is still locked / in use by another process
  57.                     [System.IO.FileStream]$fileStream = [System.IO.File]::Open( $fsEvent.FullPath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read)
  58.                     $fileStream.Close()
  59.                 } catch [System.IO.IOException] {
  60.                     Write-Host ("==> Item '$key' with changetype '$($fsEvent.ChangeType)' is still in use and can't be read!") -ForegroundColor Yellow
  61.                     continue
  62.                 }
  63.             }elseIf($fsItem -is [System.IO.DirectoryInfo]) {
  64.                 # directory processing
  65.             }
  66.  
  67.             $syncdFsItemEventHashT.Remove($key )
  68.             Write-Host ("==> Item '$key' with changetype '$($fsEvent.ChangeType)' has been processed and removed from hashtable.") -ForegroundColor Blue
  69.  
  70.         } catch {
  71.             Write-Host ($_ | Format-List * | Out-String ) -ForegroundColor red
  72.         }
  73.     }
  74. }
  75.  
  76. [void] (Register-ObjectEvent -InputObject $fileSystemWatcher -EventName 'Created' -SourceIdentifier 'FSCreated' -Action $fileSystemWatcherAction)
  77. [void] (Register-ObjectEvent -InputObject $fileSystemWatcher -EventName 'Changed' -SourceIdentifier 'FSChanged' -Action $fileSystemWatcherAction)
  78. [void] (Register-ObjectEvent -InputObject $fileSystemWatcher -EventName 'Renamed' -SourceIdentifier 'FSRenamed' -Action $fileSystemWatcherAction)
  79. [void] (Register-ObjectEvent -InputObject $fileSystemWatcher -EventName 'Deleted' -SourceIdentifier 'FSDeleted' -Action $fileSystemWatcherAction)
  80.  
  81.  
  82.  
  83. Write-Host "Watching for changes in '$fileSystemWatcherDirPath'.`r`nPress CTRL+C to exit!"
  84. try {
  85.     do {
  86.         Wait-Event -Timeout 1
  87.  
  88.         if ($syncdFsItemEventHashT.Count -gt 0) {
  89.             Write-Host "`r`n"
  90.             Write-Host ('-' * 50) -ForegroundColor Green
  91.             Write-Host "Collected events in hashtable queue:" -ForegroundColor Green
  92.             $syncdFsItemEventHashT.Values | Format-Table | Out-String
  93.         }
  94.  
  95.         # Process hashtable items and do something with them (like copying, ..)
  96.         .$fSItemEventProcessingJob
  97.  
  98.     } while ($true)
  99.  
  100. } finally {
  101.     # unregister
  102.     Unregister-Event -SourceIdentifier 'FSChanged'
  103.     Unregister-Event -SourceIdentifier 'FSCreated'
  104.     Unregister-Event -SourceIdentifier 'FSDeleted'
  105.     Unregister-Event -SourceIdentifier 'FSRenamed'
  106.  
  107.     # dispose
  108.     $FileSystemWatcher.EnableRaisingEvents = $false
  109.     $FileSystemWatcher.Dispose()
  110.     Write-Host "`r`nEvent Handler removed."
  111. }
Add Comment
Please, Sign In to add comment