Is there a Powershell command to check if a file is in use by another user? If not, what would it take to write a script that can?
Asked
Active
Viewed 8,724 times
4
-
Possible dupe of: https://stackoverflow.com/questions/958123/powershell-script-to-check-an-application-thats-locking-a-file – mikemaccana Aug 13 '18 at 13:27
-
Possible duplicate of [PowerShell script to check an application that's locking a file?](https://stackoverflow.com/questions/958123/powershell-script-to-check-an-application-thats-locking-a-file) – mikemaccana Aug 13 '18 at 13:27
3 Answers
6
You can never tell if a file is currently being used only that it was recently being used. The reason why is that the moment the script returns the file could be closed by whatever program was previously using it. Writing scripts like this will only lead to flaky behavior.
A much better approach is to just do whatever the script was going to do if the file wasn't in use and catch the exceptions that result from a use conflict. The end result will be a much simpler and more reliable program.

JaredPar
- 733,204
- 149
- 1,241
- 1,454
-
4Yes but sometimes you want to know which process has the file open so you can report that in your error handling. This can make it a bit easier to debug why some script failed in the middle of the night. – Keith Hill Aug 26 '10 at 17:34
4
There isn't a built-in command that I'm aware of however there are several tools you can use for this:
net file
From SysInternals on Technet (psfile and handle):
psfile.exe # lists and allows you to close remotely opened files
handle.exe | select-string ': File'

Keith Hill
- 194,368
- 42
- 353
- 369
1
I find that using the SysInternals "ListDlls.exe" is pretty easy and convenient:
c:\SysInternals\Listdlls.exe -d AssemblyInUse.dll
ListDLLs v3.1 - List loaded DLLs
Copyright (C) 1997-2011 Mark Russinovich
Sysinternals - www.sysinternals.com
----------------------------------------------------------------------------
powershell.exe pid: 7296
Command line: "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe"
I hope that helps!

derekerdmann
- 17,696
- 11
- 76
- 110

Brandon Hawbaker
- 534
- 5
- 5
-
Isn't this just for DLL's? My question was about arbitrary files. – derekerdmann Aug 08 '13 at 21:12
-
You are correct Derek, this handles dll files which was useful when I wanted to know if I could import a powershell module or not. If you want to check any file, I'm sure you can adapt this C# logic in powershell with your own function: http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use Also, if you want to go further and gain access to a locked file you can try unlocking it also: http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx – Brandon Hawbaker Aug 30 '13 at 15:37