FileSystemWatcher detect when file is moved to folder

那年仲夏 提交于 2019-12-11 04:42:18

问题


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
}

回答1:


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


来源:https://stackoverflow.com/questions/38877225/filesystemwatcher-detect-when-file-is-moved-to-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!