Skip to content

Instantly share code, notes, and snippets.

@scriptingstudio
Last active January 1, 2026 18:14
Show Gist options
  • Select an option

  • Save scriptingstudio/0154d6a59b01568d89dbb9a8b673d8a7 to your computer and use it in GitHub Desktop.

Select an option

Save scriptingstudio/0154d6a59b01568d89dbb9a8b673d8a7 to your computer and use it in GitHub Desktop.
Simple File Lock Tester
function Test-FileLock ([string]$Path, [int]$TimeOutMs, [int]$Count) {
$timeout = $TimeOutMs
if ($timeout -lt 0) {$timeout = 0}
if ($Count -gt 0) {$Count--} else {$Count = 0}
do {
try {
$OFile = [System.IO.FileInfo]::new($Path)
$OStream = $OFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
if ($OStream) {$OStream.Close()}
return $false
} catch {
if (-not $OFile.Length) {return $false} elseif (-not $timeout) {return $true}
}
if ($timeout) {Start-Sleep -Milliseconds $timeout; $timeout = 0}
if ($Count -and $timeout -eq 0) {$timeout = $TimeOutMs; $Count--}
} while ($timeout -gt 0)
$true
} # END Test-FileLock
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment