Question

I am having an issue with IO.FileSystemWatcher. I have a script that when file copies to a certain directory it processes that file and copies it to another folder on network. But there is a problem, it starts copying as soon as a fsw fires oncreate event, which generates an error (file is open) and I want it to start only after file has finished copying. Rename and delete works properly. cloud.ps1 is script that processes file and copies it. This is the code for monitor script:

$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)"
}
Was it helpful?

Solution

You can put in a loop to start checking to see if you can get a write lock on the file:

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

As long as the file is being written to, you won't be able to get a write lock, and the Try will fail. Once the write is complete and the file is closed, the OpenWrite will succeed, the loop will break and you can proceed with copying the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top