views:

59

answers:

3

How can I determine whether a file is in use via VBScript or a batch file? It can be a separate utility.

I've had a look at Handle but sometimes the handles don't line up with filenames, e.g. some DLLs, and it doesn't do partial searches (though I could presumably use some of the text processing utils on its full output to handle that side of things).

+1  A: 

Can you simply attempt to do whatever you want to do to the file, and report an error if it fails with a sharing violation?

"It's easier to ask forgiveness than it is to get permission." - Grace Hopper

Or if you want to know in advance whether an attempt to do something destructive will succeed, you could attempt to do something non-destructive that requires the same permissions. So if you want to know whether you can overwrite a file, try to open it for appending but don't write anything.

Whatever you do, you'll need to beware race conditions - what if someone else opens the file between your test and your actual operation?

RichieHindle
A: 

Try this:

@echo off
echo.N|copy /-y NUL "%~1">NUL
if not errorlevel 1 echo not in use
if errorlevel 1 echo in use

Credit: DosTips.com :IsFileOpen

Rubens Farias
This definitely did not work. It was reporting everything as "not in use".
dlanod
There are several "file open" types; I think this method just work for exclusive locks, as I tested with an `Access LDB` file and it reported "in use"; I'm running Windows 2008
Rubens Farias
A: 

What I have ended up using is ListDLLs. Running "listdlls -d | find /c "pid" > temp.txt" and then testing whether there's any data in temp.txt seems to determine whether or not a file is in use successfully.

dlanod