Public/ps1/Files/Start-ApprxrFileWatcher.ps1

<#
    .SYNOPSIS
    Starts a file watcher for a specific Apprxr location by name.
 
    .DESCRIPTION
    Checks if a watcher job for the given location is already running and stops it before starting a new watcher job for that location. Uses Watch-ApprxrFolder to monitor the specified folder and filter.
 
    .PARAMETER Name
    The unique name of the file watcher location to start.
 
    .EXAMPLE
    Start-ApprxrFileWatcher -Name 'Location1'
    Starts a watcher for 'Location1', stopping any existing watcher job for that name first.
 
    .NOTES
    This function is part of the Apprxr file watcher management system.
#>

function Start-ApprxrFileWatcher {
    param(
        [Parameter(Mandatory)]
        [string]$Name
    )
    $locations = Get-ApprxrFileWatcherLocations
    if (-not $locations.ContainsKey($Name)) {
        Log "No file watcher location found with name: $Name"
        return
    }
    $config = $locations[$Name]
    $inputFolder = $config.InputFolder
    $filters = $config.Filter
    if (-not $filters) { $filters = '*' }
    if ($inputFolder) {
        # Stop any running watcher jobs for this location
        $jobs = Get-Job | Where-Object { $_.Name -like "Apprxr$Name*" }
        foreach ($job in $jobs) {
            try {
                Stop-Job $job -ErrorAction SilentlyContinue
                Remove-Job $job -ErrorAction SilentlyContinue
                Log "Stopped existing watcher job: $($job.Name) for location: $Name"
            } catch {
                Log "Failed to stop watcher job: $($job.Name) for location: $Name. Error: $_"
            }
        }
        if ($filters -is [string]) { $filters = @($filters) }
        foreach ($filter in $filters) {
            Log "Starting watcher for: $Name ($inputFolder) with filter: $filter"
            Start-Job -Name ("Apprxr$Name" + [guid]::NewGuid().ToString('N')) -ScriptBlock {
                param($folder, $filter)
                Import-Module $using:PSModulePath
                Watch-ApprxrFolder -Path $folder -Filter $filter
            } -ArgumentList $inputFolder, $filter | Out-Null
        }
    }
}