PowerShell: Find Process IDs of a Locked File and Kill It

There’s a newer iteration of this function here.

$targetFile='C:\Users\kimconnect\Desktop\testfile.csv'

function killPidLockedFile($filename){
    
    if (!(Get-Command handle.exe -ErrorAction SilentlyContinue)) {
        if (!(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))    
        }
    choco install systernals -y
    }

    function findPidOfFile{
	        param($handles,$filename)
            $lockingPids=@();
            $lastKnownPid="";
	        foreach ($line in $handles) {
                $lastKnownPid=.{
                    [void]($line -match "pid:\s(.*)\s");
                    if ($matches[1]){return $matches[1]}
                    }
		        if ($line -like "*$filename*") {
			        return $lastKnownPid;
                    }
	             }
            }

    $file=$(New-Object System.IO.FileInfo $filename)
    try{
        $fileHandle = $file.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
        $fileHandle.Close() # if file handle is open, it means that file is not locked
        }catch{
            $handles = handle.exe;
            if (!($handles)){
                if (!(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
                    Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))};
                choco install sysinternals -y;
                $handles = handle;
                }
            $lockingPids=findPidLockedFile $handles $filename;
            if ($lockingPids){
                write-host "Now killing procees ID: $lockingPids";
                $lockingPids|%{taskkill /F /PID $_}
                }else{
                    write-host "$filename is currently as NOT being locked";
                    }
        }
}

killPidLockedFile $targetFile

Sample Output:

Now killing procees ID: 61808
SUCCESS: The process with PID 61808 has been terminated.

Deprecated function:

# Find-Processes-Of-Locked-Files.ps1

$lockedFile="C:\temp\yamama.ost"

# First, gather all system handles
$handles = handle.exe;
if (!($handles)){
if (!(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))};
choco install sysinternals -y;
$handles = handle;
}

# Requires handle.exe from Systernals. returns pid
function findPidLockedFile{
param($lockedFile)
$scrollingPid="";
$lockingPids=@();
foreach ($line in $handles) {
if ($line -like "*pid:*") {$scrollingPid=$line}
if ($line -like "*$lockedFile*") {
#[void]($scrollingPid -match "(.*)\spid:");
[void]($scrollingPid -match "pid:\s(.*)\s");
$lockingPids+=,$matches[1];
}
}
return $lockingPids|get-unique
}

$lockingPids=findPidLockedFile $lockedFile;
write-host "Here are the Pids for you to kill:`r`n$lockingPids"

Leave a Reply

Your email address will not be published. Required fields are marked *