8

I have a Unix shell script which will kill any process that is accessing a folder:

fuser -k ..\logs\*

Is there a Windows batch script equivalent to this? I am aware of TASKKILL but I'm not sure if it will do what I need. Does anyone know if this is possible with Windows shell?

ChesuCR
  • 9,352
  • 5
  • 51
  • 114
Matt
  • 2,503
  • 4
  • 31
  • 46

2 Answers2

7

Not with built-in tools (there is nothing that can enumerate handles), but you can use the Sysinternals Handle tool to get a list of the PIDs that have open handles on a file. You can then parse the output with FOR /F and use TASKKILL to end the processes.

Example:

for /f "skip=4 tokens=3" %i in ('handle ..\logs\') do taskkill /pid %i

skip=4 skips the copyright information in Handle's output and tokens=3 picks out the PID from each line of output. The rest are self-explanatory.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • Thanks for the comment. It needs to be done entirely in Windows shell with no other tools as I need to deploy this to many machines which I cannot install things on. I didn't think it was possible with just plain shell either so I'll have to convince my team to install something like this on the machines. – Matt Aug 05 '13 at 15:34
  • 1
    @Matt: Note that Handle (and any other tool that can do this) must run with administrative privileges. – Jon Aug 05 '13 at 15:34
2

I found a fuser for Windows. Check this link to Sourceforge:

Many would ask, "why not use handle.exe from SysInternals?"

While being a truly excellent utility (as all of SysInternals stuff is), it falls short -- at least for me -- for a couple of reasons:

  1. It does filename pattern matching. I need it to do exact file matches with partial input. For example, when I'm in the C:\TMP directory, and I'm checking on a file named out.dat, I want it to see if the file C:\TMP\OUT.DAT is being used without having to type full path in. I think even if you type in the full path for handle.exe, it will still do pattern matching.

  2. handle.exe seems to always exit 0. For scripting purposes, I need it to exit 1 if the file is not being used, but 0 if it is. This is very useful in scripts.

ChesuCR
  • 9,352
  • 5
  • 51
  • 114