1

I'm having trouble with a script that's monitoring a folder. FileSystemWatcher only seems to detect when a file is being copied to the folder, not when it's just being moved to it from the same drive. Is there a way to detect this?

$desFolder   = "H:\Media"
$ExFolder    = "H:\Monitor"

$Filter       = '*.*'
$fsw = New-Object IO.FileSystemWatcher $ExFolder, $Filter 
$fsw.IncludeSubdirectories = $true

$fswOnChange = Register-ObjectEvent -InputObject $fsw -EventName Changed -SourceIdentifier FileUpdated -Action {
    $File =  Get-Item $EventArgs.FullPath
    if($File.Name -imatch '\.(?:mp4|mkv)$' -and $file.Name -match '.*?S\d+E+'){
        Start-Sleep -s 1
        if(Test-FileReady $File.FullName){
            Move-Files $File
        }
    }
}
function global:Test-FileReady {
    Param([parameter(Mandatory=$true)][string]$Path)
    if (Test-Path  -LiteralPath $Path) {
      trap {
        return $false
      }
      $stream = New-Object system.IO.StreamReader $Path
      if ($stream) {
        $stream.Close()
        return $true
      }
    }
}
function global:Move-Files{
    Param([parameter(Mandatory=$true)][System.IO.FileInfo]$File)
    Write-Host $File.Name
}
FuSiOn
  • 23
  • 5

1 Answers1

3

Try using Renamed and Created events as well.

BTW, the IO.FileSystemWatcher docs say:

The component will not watch the specified directory until the Path is set, and EnableRaisingEvents is true

$fsw.EnableRaisingEvents = $true
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • 'Created' seems to work for moved files that are directly moved in to the folder. But when a folder with files is moved in the directory it only triggers on the folder not the files contained in it. I can work with that but is there maybe a way to let it trigger on each file in the folder? – FuSiOn Aug 10 '16 at 16:09
  • @FuSiOn, apparently, moving a folder is one atomic operation on the file system level, so it triggers just one event. You'll have to enumerate the moved folders manually. – wOxxOm Aug 10 '16 at 16:43