Last active
January 1, 2026 18:14
-
-
Save scriptingstudio/0154d6a59b01568d89dbb9a8b673d8a7 to your computer and use it in GitHub Desktop.
Simple File Lock Tester
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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