Private/ps1/Watch-ApprxrFolder.ps1
|
<##
.SYNOPSIS Watches a folder for new incoming files and triggers an action when a new file is detected. .DESCRIPTION Uses .NET FileSystemWatcher to monitor a specified folder for new files. When a new file is created, the script outputs the file name or performs a custom action. .PARAMETER Path The folder path to watch for new files. .PARAMETER Filter The file filter (e.g., *.txt) to watch for. Default is * (all files). .EXAMPLE Watch-ApprxrFolder -Path 'C:\Logs' -Filter '*.log' Watches the C:\Logs folder for new .log files. ##> function Watch-ApprxrFolder { param( [Parameter(Mandatory)] [string]$Path, [string]$Filter = '*', [string]$InProgressFolder ) # Create a new FileSystemWatcher object $watcher = New-Object System.IO.FileSystemWatcher $watcher.Path = $Path $watcher.Filter = $Filter $watcher.EnableRaisingEvents = $true $watcher.IncludeSubdirectories = $false # Define the action to take when a new file is created $onCreated = Register-ObjectEvent $watcher 'Created' -Action { $filePath = $Event.SourceEventArgs.FullPath Log "New file detected: $filePath" if ($using:InProgressFolder) { if (-not (Test-Path $using:InProgressFolder)) { New-Item -ItemType Directory -Path $using:InProgressFolder | Out-Null } $destPath = Join-Path $using:InProgressFolder ([System.IO.Path]::GetFileName($filePath)) try { Move-Item -Path $filePath -Destination $destPath -Force Log "Moved $filePath to $destPath" } catch { Log "Failed to move $filePath to $($destPath): $_" } } # Place custom logic here (e.g., process the file) } Log "Watching folder: $Path for new files matching: $Filter. Press Ctrl+C to stop." try { while ($true) { Start-Sleep -Seconds 1 } } finally { Unregister-Event -SourceIdentifier $onCreated.Name $watcher.Dispose() } } |