Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One way to avoid file locks caused by running the script on a timer is to use an event driven approach using a file system watcher. It has the ability to execute code when an event such as a new file is created in the folder you are monitoring.</p> <p>To run code when the file is finished copying you would need to listen for the <code>changed</code> event. There is a slight issue with this event in that it fires once when the file begins copying and again when it is finished. I got an idea to work around this chicken/egg problem after checking out the module Mike linked to in the comments. I've updated the code below so that it will only fire off code when file has fully been written.</p> <p>To try, change <code>$folderToMonitor</code> to the folder you want to monitor and add some code to process the file.</p> <pre><code>$processFile = { try { $filePath = $event.sourceEventArgs.FullPath [IO.File]::OpenRead($filePath).Close() #A Way to prevent false positive for really small files. if (-not ($newFiles -contains $filePath)) { $newFiles += $filePath #Process $filePath here... } } catch { #File is still being created, we wait till next event. } } $folderToMonitor = 'C:\Folder_To_Monitor' $watcher = New-Object System.IO.FileSystemWatcher -Property @{ Path = $folderToMonitor Filter = $null IncludeSubdirectories = $true EnableRaisingEvents = $true NotifyFilter = [System.IO.NotifyFilters]'FileName,LastWrite' } $script:newFiles = @() Register-ObjectEvent $watcher -EventName Changed -Action $processFile &gt; $null </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload