Copy-Item does not work with FileSystemWatcher

本小妞迷上赌 提交于 2020-01-06 08:19:50

问题


I'm trying to create a watch folder on a network share that simply copies files (300mb-20gb) in size to a destination folder. The FileSystemWatcher and subscription works great with small files (i.e. 1-3kb). However, larger files do not copy. I do see a copy is triggered in the verbose stream, but no file is copied to the destination folder.

 $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
 }

回答1:


Combination of issue were at hand. Firstly thank you JohnLBevan for pointing out LastWrite should be the notifyfilter to use. Also found that in this case copy-item does not wait for the file transfer in the source directory to close. I fixed this by putting in a while loop waiting for the file to be locked:

 ##################### 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}


来源:https://stackoverflow.com/questions/44583244/copy-item-does-not-work-with-filesystemwatcher

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