Why is powershell script is running twice?

123 Views Asked by At

I have a powershell script which will execute .exe file on file change in specific directory, but when the change happens, it executes 2 times one after the other. Can you help me? Here's the script:

$folderToWatch = "C:\Users\user\FTP"
$fileToWatch = "file.txt"  

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $folderToWatch
$watcher.Filter = $fileToWatch
$watcher.EnableRaisingEvents = $true

$action = {
    $executablePath = "C:\DotNet\Program.exe"
    $filePath = $Event.SourceEventArgs.FullPath
    Write-Host "New or modified file detected: $filePath"
    Write-Host "Executable path: $executablePath"
    try {
        Start-Process -FilePath $executablePath -Wait
    } catch {
        Write-Host "Error starting the process: $_"
    }
}

Register-ObjectEvent -InputObject $watcher -EventName Changed -Action $action
0

There are 0 best solutions below