Unlock File __hot__ | Powershell
You need to know exactly which application (Word, Notepad, a rogue service) is holding the lock before acting. 3. The "Force Unlock" via Safe Volume Opening For advanced scenarios, you can use .NET's FileShare.None method. This doesn't break an existing lock, but it can prevent future locks or test if a file is locked:
function Unlock-File { param( [Parameter(Mandatory)] [string]$FilePath, [string]$HandlePath = "handle64.exe" ) if (-not (Test-Path $HandlePath)) { Write-Error "handle64.exe not found. Download from Sysinternals." return }
& "C:\path\to\handle64.exe" -accepteula "C:\path\to\your\file.pdf" The output will look like: notepad.exe pid: 8764 type: File C:\path\to\your\file.pdf powershell unlock file
# Force close all handles to a specific file (use with extreme caution!) & "C:\path\to\handle64.exe" -accepteula -c "C:\path\to\file.pdf" -y The -y flag suppresses confirmation. This immediately rips the lock away from the owning process. The process may crash or lose unsaved data, but the file will be unlocked.
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. You need to know exactly which application (Word,
A locked file is blocking a critical automated deployment or build script, and you're willing to risk the owning process failing. 5. A Complete PowerShell Unlock Function Here’s a function that combines detection and safe unlocking:
Stop-Process -Name explorer -Force Start-Process explorer.exe You know the lock is caused by Explorer (e.g., an image or video file preview stuck open). 2. Finding the Culprit: Identifying the Locking Process PowerShell can't directly break a lock without help, but it can tell you who has the lock. For this, we use the Handle tool from Sysinternals (Microsoft’s official utility suite). This doesn't break an existing lock, but it
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"