0

I am able to successfully use System.IO.FileSystemWatcher to watch a folder and subdirectories for created files but when I try and run a batch file using Start Process it runs once but then never triggers again. I modified an answer from here.

Here is my powershell script

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\lectures"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true  

$action = { $path = $Event.SourceEventArgs.FullPath
            Write-Host "Event Fired"
            $ext = [io.path]::GetExtension($path)
            if($ext -eq ".wma"){
                $file = [io.path]::GetFileNameWithoutExtension($path)
                $folder = Split-Path(Split-Path $path -Parent) -Leaf
                $date = Get-Date -UFormat "%Y-%m-%d"
                $newName = $folder + "_" + $date + $ext
                $newPath = Rename-Item -path $path -newname $newName -PassThru
                Start-Process "C:\lectures\deploy.bat" $newPath
            }
          }

Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {
    Write-Host "Still Alive"
    sleep 5
}

Here is the batch file I am running

@echo off
CD %~dp1
ffmpeg -i %~nx1 %~n1.mp3 -loglevel panic
del %1
REM Winscp.com /ini=null /script=uploadScript.txt /parameter %~n1.mp3

The powershell script continues to run after it runs the process and the process seems to be exiting properly. How do I make it continue to process events?

N1mr0d
  • 101
  • 1
  • I need the powershell script to watch the folder and then do something when a new file is created. I don't need to pass any arguments to powershell I need to call a batch fill from powershell – N1mr0d Aug 29 '17 at 18:55
  • Seems to work fine on this side. Are you expecting it to rename the `$watcher.Path =` to a different value and thus the `while ($true) {` is false and thereby terminates. With that type of loop it is endless only when result is true so are you sure your other logic is doing what you expect with the folder name of `\_2017-08-29`. You might consider using a `IF ELSE` logic to handle result that may not always be true based on what the other logic does with the folder name the files are in from what I see when I tested. – Vomit IT - Chunky Mess Style Aug 29 '17 at 21:39
  • Check that `Rename-Item -path $path -newname $newName -PassThru` is doing what you are expecting if `.wma` exist. – Vomit IT - Chunky Mess Style Aug 29 '17 at 21:41
  • Do you have an update or any new news on this task? Per my testing and findings, that's what I wrote in the above comments. – Vomit IT - Chunky Mess Style Sep 01 '17 at 02:25

0 Answers0