function Test-FileLock { param([string]$FilePath) try { $file = [System.IO.File]::Open($FilePath, 'Open', 'Read', 'None') $file.Close() return $false # File is not locked } catch { return $true # File is locked } } Test-FileLock "C:\locked.docx"
Now you can stop the offending process gracefully or forcefully: powershell unlock file
Few things are as frustrating as trying to delete, move, or edit a file, only to be met with the error: "The action cannot be completed because the file is open in another program." or edit a file
This is useful for scripts that need to wait until a file is free (e.g., a backup script waiting for a database to release a log file). Warning: This is risky. Do not run this on your C: drive. powershell unlock file