2014-01-30 93 views
0

我遇到IO.FileSystemWatcher問題。我有一個腳本,當文件複製到某個目錄時,它會處理該文件並將其複製到網絡上的另一個文件夾中。但是有一個問題,一旦fsw觸發oncreate事件就會開始複製,這會產生一個錯誤(文件已打開),我希望它只在文件完成複製後才能啓動。重命名和刪除工作正常。 cloud.ps1是處理文件並將其複製的腳本。 這是監控腳本代碼:Powershell:文件完成複製後執行腳本

$watch = '\\HR-ZAG-SR-0011\ACO\ACO2\99. BOX' 
$watcher = New-Object System.IO.FileSystemWatcher 
$watcher.Path = $watch 
$watcher.IncludeSubdirectories = $true 
$watcher.EnableRaisingEvents = $true 

$changed = Register-ObjectEvent $watcher "Changed" -Action { 
# Write-Host "Changed: $($eventArgs.ChangeType)" 
# $watch\cloud.ps1 modify "$($eventArgs.FullPath)" 
} 
$created = Register-ObjectEvent $watcher "Created" -Action { 
    Write-Host "Created: $($eventArgs.FullPath)" 
    .\cloud.ps1 create "$($eventArgs.FullPath)" 
} 
$deleted = Register-ObjectEvent $watcher "Deleted" -Action { 
    Write-Host "Deleted: $($eventArgs.FullPath)" 
    .\cloud.ps1 delete "$($eventArgs.FullPath)" 
} 
$renamed = Register-ObjectEvent $watcher "Renamed" -Action { 
    Write-Host "Renamed: $($eventArgs.OldFullPath) to $($eventArgs.FullPath)" 
    .\cloud.ps1 rename "$($eventArgs.OldFullPath)" "$($eventArgs.FullPath)" 
} 

回答

1

你可以把一個循環開始檢查,看看是否可以獲取有關文件的寫鎖:

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

只要文件正在寫入,您將無法獲得寫入鎖定,並且嘗試將失敗。一旦寫入完成並且文件關閉,OpenWrite將會成功,循環將會中斷,您可以繼續複製文件。