Use PowerShell to find out which process locks a file

When working with Visual Studio, there are quite a few occasions when I faced an annoying error at build time:

Unexpected error creating debug information file ‘debug_path\file.PDB’ — ‘debug_path\file.PDB: The process cannot access the file because it is being used by another process.

There are a couple of workarounds for solving the problem, as shown in this link.

Anyway, if you would like to know which process is locking that file (quite helpful on SharePoint development machines, where you have several w3wp.exe, i.e. IIS worker processes), here’s a short PowerShell script which let’s you input the path of the locked file and outputs the “culprit” process:

$lockedFile="C:\Windows\System32\wshtcpip.dll"
Get-Process | foreach{$processVar = $_;$_.Modules | foreach{if($_.FileName -eq $lockedFile){$processVar.Name + " PID:" + $processVar.id}}}
Advertisements

7 responses to “Use PowerShell to find out which process locks a file

  1. This is very nice, but of course it assumes you know what application is locking the file – in this case w3wp. How would you go about finding out which process is locking the file without knowing the application? Is that possible?.

    • Hi Salamander,
      First of all, thanks for the comment. Actually, you have a point, I mistakenly published the script with the added w3wp filter because that’s one way I encountered this error and there were multiple instances of the process running on the target machine. The script should only take as an input the path of the file which is locked, it should parse all the processes (not only the w3wp filtered ones, so you should use a simple Get-Process in the pipeline, instead of Get-Process w3wp) and outputs the process that blocks that file (which is what we are looking for). I updated the script considering your remark.

  2. Doh! Of course it works. Thanks for graciously pointing that out and not flaming my apparent inability to try the obvious before posting…!

  3. Thought this was going to be a big help but it only works with dlls (or modules as they are called). Is there a way of getting this to show other files (in my case powershell script files) that are locked. In Process Monitor you can use the handles section so i can going to look into that some more,

    Thanks for contributing.

  4. Pingback: What is locking my file or folder? | YASAB·

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s