2017-06-16 78 views
0

我試圖在網絡共享上創建一個監視文件夾,它只是將文件(300mb-20gb)大小複製到目標文件夾。 FileSystemWatcher和訂閱對小文件(即1-3kb)非常有用。但是,較大的文件不會複製。我確實看到在詳細流中觸發了一個副本,但沒有文件被複制到目標文件夾。Copy-Item不適用於FileSystemWatcher

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

您在最後一次訪問文件時觸發,而不是最後一次寫入文件。由於複製項目將訪問該文件,我猜測這會導致它跳閘。在'NotifyFilter'中使用'LastWrite' .. – JohnLBevan

+1

謝謝John,我試着將LastWrite作爲NotifyFilter。它仍然不會複製超過2-3kb的任何文件。 – user6705306

+0

另一個想法;觸發上述腳本中的Copy-Item時是否只能看到此問題;或者在使用Copy-Item從同一個源到目的地時看到相同的問題?是那些工作和那些不是他們的文件大小之間的唯一區別?對不起,有這麼多的問題;可悲的是,我還沒有機會爲自己測試你的代碼,或者對FSW沒有足夠的瞭解,沒有測試就發現任何問題。 – JohnLBevan

回答

2

問題的結合就在眼前。首先感謝JohnLBevan指出LastWrite應該是使用的notifyfilter。還發現在這種情況下,複製項目不會等待源目錄中的文件傳輸關閉。我通過放入一個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} 
+0

很高興看到您找到解決方案。看起來這些人達到了相同的結論/這是一個常見問題:https://www.intertech.com/Blog/avoiding-file-concurrency-using-system-io-filesystemwatcher/。因此,我向Dot Net GitHub repo提交了一個問題(建議):https://github.com/Microsoft/dotnet/issues/437 – JohnLBevan