【问题标题】:Copy-Item does not work with FileSystemWatcherCopy-Item 不适用于 FileSystemWatcher
【发布时间】:2017-06-16 07:23:05
【问题描述】:

我正在尝试在网络共享上创建一个监视文件夹,该文件夹只是将文件 (300mb-20gb) 大小复制到目标文件夹。 FileSystemWatcher 和订阅非常适用于小文件(即 1-3kb)。但是,较大的文件不会复制。我确实看到详细流中触发了副本,但没有文件被复制到目标文件夹。

 $Folder = "\\10.11.233.91\vol_tx01\delivered_media"
 $Filter = "*.mxf"
 $destination = "C:\Users\Leeds TX 11\Desktop\support\Testy"
 $Watcher = New-Object IO.FileSystemWatcher $Folder, $Filter -Property @{
     NotifyFilter = [IO.NotifyFilters]'Filename, LastAccess'
 }

 $onCreated = Register-ObjectEvent $Watcher Created -SourceIdentifier `
 FileCreated -Action {
     $path = $event.SourceEventArgs.FullPath
     $name = $event.SourceEventArgs.Name
     $ChangeType = $event.SourceEventargs.ChangeType
     $Timestamp = $event.TimeGenerated
     Write-Host "The file '$name' was $ChangeType at $Timestamp"
     Copy-Item $path -Destination $destination -Force -Recurse -Verbose
 }

【问题讨论】:

  • 您是在最后一次访问文件而不是最后一次写入文件时触发。由于 copy-item 将访问该文件,我猜这会导致它跳闸。在您的NotifyFilter 中使用LastWrite..
  • 感谢 John,我尝试将 LastWrite 作为 NotifyFilter。它仍然不会复制任何超过 2-3kb 的文件。
  • 另一个想法;您是否仅在从上述脚本触发 Copy-Item 时看到此问题?或者您在使用从同一来源到目的地的 Copy-Item 时是否看到相同的问题?那些工作的和那些不工作的文件大小之间的唯一区别是什么?抱歉问了这么多问题;遗憾的是,我还没有机会为自己测试您的代码/对 FSW 的了解还不够,无法在没有测试的情况下发现任何问题。

标签: powershell filesystemwatcher


【解决方案1】:

问题的组合就在眼前。首先感谢 JohnLBevan 指出 LastWrite 应该是要使用的 notifyfilter。还发现在这种情况下copy-item不会等待源目录中的文件传输关闭。我通过放置一个等待文件被锁定的while循环来解决这个问题:

 ##################### DANGER BOX ####################################

    $Folder = "C:\Users\Leeds TX 12\Desktop\Source" #Source dir
    $Filter = "*.mxf" # MXF Filter
    $destination = "C:\Users\Leeds TX 12\Desktop\Destination" # Destination dir



################### Watch for file system events###########################

$Watcher = New-Object IO.FilesystemWatcher $Folder, $Filter -Property @{
NotifyFilter = [IO.NotifyFilters]'LastWrite, Filename'
}

################### Register filesystemwatcher & subscribe to notifyfilters ################# 

$onCreated = Register-ObjectEvent $Watcher Created -SourceIdentifier filecreated -Action {
$path = $event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$ChangeType = $Event.SourceEventargs.ChangeType
$Timestamp = $event.TimeGenerated
write-host "The file '$name' was $ChangeType at $Timestamp" # Debug

################# Wait for file lock collapse #########################################

while($True)
{
Try {
      [IO.File]::OpenWrite($path).Close()
      Break
      }
   Catch { Start-Sleep -Seconds 1}
   }

#################### Copy item #############################

Copy-item $path -Destination $Destination -force -Recurse -Verbose}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 2020-12-20
  • 1970-01-01
  • 2021-10-26
  • 2020-10-15
  • 1970-01-01
相关资源
最近更新 更多