Set-StrictMode -Version Latest . "$PSScriptRoot\helpers.ps1" . "$PSScriptRoot\process-zip.ps1" $Settings = Import-Settings $folder = $Settings.DownloadWatchFolder $pattern = $Settings.ZipPattern if (!(Test-Path $folder)) { Write-Log "DownloadWatchFolder does not exist: $folder" "ERROR" exit 1 } Write-Log "Watching $folder for $pattern" # Process anything already waiting. & "$PSScriptRoot\run-once.ps1" $watcher = New-Object System.IO.FileSystemWatcher $watcher.Path = $folder $watcher.Filter = $pattern $watcher.IncludeSubdirectories = $false $watcher.EnableRaisingEvents = $true $action = { $path = $Event.SourceEventArgs.FullPath Start-Sleep -Seconds 1 try { & $using:PSScriptRoot\process-zip.ps1 $path } catch { . "$using:PSScriptRoot\helpers.ps1" Write-Log "Watcher error for $path : $_" "ERROR" } } $created = Register-ObjectEvent -InputObject $watcher -EventName Created -Action $action $changed = Register-ObjectEvent -InputObject $watcher -EventName Changed -Action $action $renamed = Register-ObjectEvent -InputObject $watcher -EventName Renamed -Action $action try { while ($true) { Start-Sleep -Seconds 5 } } finally { Unregister-Event -SourceIdentifier $created.Name -ErrorAction SilentlyContinue Unregister-Event -SourceIdentifier $changed.Name -ErrorAction SilentlyContinue Unregister-Event -SourceIdentifier $renamed.Name -ErrorAction SilentlyContinue $watcher.Dispose() }