Clean up a remote machine's temporary directory: How do I identify files that are in use? (Powershell)

Go To


I have a number of remote machines whose temporary directories get full. (The are Selenium / webdriver grid remotes). I have a powershell script that identifies the files and directories that need to be cleaned. The command in use looks something like this (excluding complexities of the various machines and directories):

gci $env:TEMP -Recurse| Remove-Item -ErrorAction Continue -Recurse

The problem is that this takes far too long when some files are in use. Locally, I could join to the output of handles (parsing would be a little ugly), but that would be more complicated on a remote machine. Among other things, I'd need to verify that WinRM was configured correctly, handles was in path, etc.

Is there a simpler way to identify that a file is in use? Ideally one that can be filtered on via Powershell (which includes .NET). I'm familiar with a variety of other scripting languages (ruby, python, perl).

2012-04-03 22:06
by Precipitous
Good question. I don't know how to do what you ask. when I built a script to clean the temp dir, I decided to remove files that fit a particular set of criteria: the name conforms to a known set of patterns (*.tmp, etc), they are more than 1 week old, and a few other things - Cheeso 2012-04-04 21:30


The best tool I've found for listing open files is the SysInternals tool handle.exe e.g.:

$openFiles = @(handle $env:TEMP | Foreach {($_ -split ": ")[3]} | Select -Unique)
2012-04-03 22:26
by Keith Hill
The snippet is clever (doesn't quite work, tho. I will tweak it and re-post.). This would require executing on the remote machine, but there may be no other way - Precipitous 2012-04-06 05:01
The output of handle.exe is text so we're back to parsing text output. Depending on the version of handle.exe the output format could be different. I need to ping the SysInternals folks to provide an option to output in CSV format - Keith Hill 2012-04-06 05:12
Posted on SysInternals forum in case anybody else wants to chime in - - Keith Hill 2012-04-06 05:22
I now have a reliable handle parsing function, but there are a file files that fail (presumably they are intermittently in use) function getFileNameFromHande($handleOutput) { $start = $handleOutput.IndexOf(":\") if($Start -lt 0) { return [String]::Empty

} return $handleOutput.SubString($start - 1) - Precipitous 2012-04-06 05:53

I now have a solution that combines the handle output with last access time. I'll post the full script after I can clean it up - Precipitous 2012-04-06 06:00