mercredi 5 février 2020

If statement within FileSystemWatcher Not working in Powershell

I am trying to implement a FileSystemWatcher that contains an if statement that evaluates and argument passed to it, but it doesn't seem to be evaluating. Am I making a mistake? Here is the code:

Function Auto-Watcher
{
    param ($folder, $filter, $Program)

    $watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
        IncludeSubdirectories = $true
        EnableRaisingEvents = $true
    }

    Write-Host "Watching $folder for creation or moving of $filter files..."

    $changeAction = {
        $path = $Event.SourceEventArgs.FullPath
        $name = $Event.SourceEventArgs.Name
        $changeType = $Event.SourceEventArgs.ChangeType
        $timeStamp = $Event.TimeGenerated

        if ($Program -match "Report1") {
            Write-Host $Path "Ready for Report1 Generation"
            else {
                if ($Program -match "Report2") {
                    Write-Host Split-Path $Path "Ready for Report2 Generation"
                    else {
                        write-output "Error, not capable of matching identical strings"
                    }
                }
            }
        }

        Write-Host "The file $name was $changeType at $timeStamp"
    }
    Register-ObjectEvent $Watcher -EventName "Created" -Action $changeAction
}

I added in a Write-Output statement before the if statements that confirmed that $Program -match "Report1" was returning $true, but nothing in the if statements seems to be evaluated. What can I do?

Aucun commentaire:

Enregistrer un commentaire