Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell script to check an application that's locking a file?

Using in PowerShell, how can I check if an application is locking a file?

I like to check which process/application is using the file, so that I can close it.

like image 487
Marc Vitalis Avatar asked Jun 05 '09 21:06

Marc Vitalis


People also ask

How can I tell if a file is locked in PowerShell?

File]::OpenWrite((Resolve-Path $file). Path). close() , otherwise it will default to the home directory and become a hard to debug logic error. Note that this returns false if the file is locked, while @Dech's answer returns true if the file is locked.


2 Answers

You can do this with the SysInternals tool handle.exe. Try something like this:

PS> $handleOut = handle PS> foreach ($line in $handleOut) {          if ($line -match '\S+\spid:') {             $exe = $line         }          elseif ($line -match 'C:\\Windows\\Fonts\\segoeui\.ttf')  {              "$exe - $line"         }      } MSASCui.exe pid: 5608 ACME\hillr -   568: File  (---)   C:\Windows\Fonts\segoeui.ttf ... 
like image 72
Keith Hill Avatar answered Sep 23 '22 13:09

Keith Hill


You should be able to use the openfiles command from either the regular command line or from PowerShell.

The openfiles built-in tool can be used for file shares or for local files. For local files, you must turn on the tool and restart the machine (again, just for first time use). I believe the command to turn this feature on is:

openfiles /local on 

For example (works on Windows Vista x64):

openfiles /query | find "chrome.exe" 

That successfully returns file handles associated with Chrome. You can also pass in a file name to see the process currently accessing that file.

like image 34
Garrett Avatar answered Sep 23 '22 13:09

Garrett