PowerShell: Find Locking PID of a File

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

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

findPidOfFile $filePath

Leave a Reply

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