This PowerShell function `Wait-ForFileReady` is designed to determine when a...

August 28, 2025 at 05:12 PM

function Wait-ForFileReady { param([string]$Path, [int]$TimeoutSec = 60) $sw = [Diagnostics.Stopwatch]::StartNew() $lastSize = -1 while ($sw.Elapsed.TotalSeconds -lt $TimeoutSec) { try { if (-not (Test-Path -LiteralPath $Path)) { Start-Sleep -Milliseconds 200; continue } $info = Get-Item -LiteralPath $Path -ErrorAction Stop # If size is stable for 1 second and file can be opened for Read, consider it ready if ($info.Length -eq $lastSize -and $lastSize -ge 0) { $fs = [System.IO.File]::Open($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read) $fs.Close() return $true } $lastSize = $info.Length } catch { } Start-Sleep -Seconds 1 } return $false }

This PowerShell function Wait-ForFileReady is designed to determine when a file located at a specified path is "ready" to be accessed. It does this by implementing the following logic:

Parameters:

  • [string]$Path: The full path to the file to monitor.
  • [int]$TimeoutSec = 60: The maximum number of seconds to wait for the file to become ready (default is 60 seconds).

Process:

  1. Initialize Stopwatch: A stopwatch ($sw) is started to track the elapsed time.
  2. Monitor File Path:
    • If the file does not exist at the given path (Test-Path), the function waits briefly (200 milliseconds) and then checks again.
    • If the file exists, it queries the file's metadata using Get-Item.
  3. Determine File Readiness:
    • The function checks if the file's size ($info.Length) has stabilized (i.e., the size is the same as the last recorded size for at least 1 second).
    • If the size is stable and the file can be successfully opened in Read mode (using [System.IO.File]::Open), the function considers the file ready and exits with $true.
  4. Timeout Handling:
    • If the file does not become ready before the $TimeoutSec limit is reached, the function exits with $false.

Purpose:

This function is useful for scenarios where a process needs to wait for a file to be completely created, written, or copied into a location before further actions are taken on it (e.g., reading or processing the file). It prevents accessing a file prematurely, which could result in errors or incomplete data.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node