Get process that is locking a file

Hi, i having the following problem. In a server sometimes after stopping services, one or two files in a directory (most of the time is a dll), get lock by svchost process. I tried to create a powershell script (to use in an Azure Devops job) to find the process that is locking this file but I cann’t find it.

  1. I used handle tool. I even list all item to a text file (handle64 > fileproc.txt), and I don’t find that file

  2. I used the following code (and nothing)
    Get-Process | foreach{$processVar = $;$.Modules | foreach{if($_.FileName -eq $lockedFile){$processVar.Name + " PID:" + $}}}

  3. In Process explorer when I search for that file, I get the process id. Any ideas why in option 1 or option 2, don’t find the locked file?

  4. When I try with [System.IO.File]::Open, it throws an error, that is locked. Is that possible to get there the process id?

Get-Process does not return a full list of loaded modules. ListDlls.exe from Sysinternals is a better choice to see if a DLL is loaded in a process. Be sure that you are running it in an elevated session.

Thanks for your answer. I tried Listdlls, and is true that it returned more info (I’m running it as administrator) but it keeps without referring to that locking file. Those files are from an external supplier and probably something is wrong on that software but what i need is to kill any process that is using that diretory by script, so that i can update with a new software.

Have you tried tasklist?