title: Copy File On Creation (once complete)
body: <p>I have the below code to detect the creation of a new file and grab a copy of it.</p>
  
  <pre><code>$folder = '\\server\share\monitor_me\'
  $filter = '*.*'  
  $copyToFolder = 'C:\temp\capture\'
  
  $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
  
  #protection from previous runs
  unregister-event -SourceIdentifier FileCreated -ErrorAction SilentlyContinue
  
  Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
      $name = $Event.SourceEventArgs.Name
      $changeType = $Event.SourceEventArgs.ChangeType
      $timeStamp = $Event.TimeGenerated
      Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
      Copy-Item -Path $Event.SourceEventArgs.FullPath -Destination $copyToFolder
  }
  </code></pre>
  
  <p>Testing it with this code in a parallel session:</p>
  
  <pre><code>1..1000 `
  | %{new-object -TypeName pscustomobject -Property @{Id=$_;Name="hi"} } `
  | export-csv '\\server\share\monitor_me\test.csv'
  </code></pre>
  
  <p>...shows that the code does work; but captures the file the moment it appears rather than waiting for it to be fully populated, so I only get some of the resulting file's content.</p>
  
  <p>I could add a <code>start-sleep</code> statement; but that would lead to race conditions.</p>
  
  <p>I assume that there's a lock on the file whilst it's being written to (i.e. preventing other processes from updating the same file; but not affecting reading/copying of the file), so would ideally like to have some way to wait until that lock's removed.</p>
  
  <ul>
  <li>Is my assumption about there being a file lock for the <code>export-csv</code> process correct?</li>
  <li>Is there a way to detect when the lock's removed?</li>
  </ul>
  
  <p>Thanks in advance</p>