FileSystemWatcher检测何时将文件移动到文件夹 [英] FileSystemWatcher detect when file is moved to folder

查看:108
本文介绍了FileSystemWatcher检测何时将文件移动到文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在监视文件夹的脚本时遇到了麻烦. FileSystemWatcher似乎仅检测何时将文件复制到文件夹,而不是何时将其从同一驱动器移动到文件夹. 有没有办法检测到这个?

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
}

推荐答案

也尝试使用RenamedCreated事件.

顺便说一句, IO.FileSystemWatcher文档说:

在设置Path且EnableRaisingEvents为true之前,组件将不会监视指定的目录

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

$fsw.EnableRaisingEvents = $true

这篇关于FileSystemWatcher检测何时将文件移动到文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆