PowerShell: Find Locking PID of a File

$filePath="C:\Program Files\Google\Chrome\Application\chrome.exe"

function findPidOfFile($filepath){    
    try{
        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 sysinternals -y --ignore-checksums
        }
        $handles=handle.exe
        $matchedLines=$handles|?{$_ -like "*$filepath*"}
        $lockingPids=@();
        $lastKnownPid="";
        if($null -ne $matchedLines){
            foreach ($line in $matchedLines) {
            $lastKnownPid=.{
                [void]($line -match "pid:\s(.*)\s");
                if ($matches[1]){return $matches[1]}
                }
            if ($line -like "*$filepath*") {
                return $lastKnownPid;
                }
            }
        }else{
            write-host "$filepath does NOT currently have a locking pid"
        }
    }catch{
        write-warning $_
    }
}

findPidOfFile $filePath

Leave a Reply

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