Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a folder has no files locked by any process?

I am trying to write a PowerShell script that will check if none of the files in a particular folder is locked by any process; if true, only then delete the folder.

One way is to check locks on each file by opening them in RW mode iteratively - see if exception occurs. But that's too cumbersome.

Is there a way to check the same thing for a folder? I tried to use Remove-Item with -WhatIf flag but it's of no use because the command doesn't return any value - nor did it detect the locked files. If I try to run Remove-Item without the flag to look for exception, then it removes the free files only whereas I want to have a All or None condition.

like image 895
user167617 Avatar asked Sep 13 '25 04:09

user167617


1 Answers

As long as you're not going to distribute the solution, you could use handle.exe. It shows all files/folders in use and who is using it.

$path = "C:\Users\frode\Desktop\Test folder"

(.\handle64.exe /accepteula $path /nobanner) -match 'File'
explorer.exe       pid: 1888   type: File           F3C: C:\Users\frode\Desktop\Test folder
explorer.exe       pid: 1888   type: File          2E54: C:\Users\frode\Desktop\Test folder
notepad.exe        pid: 2788   type: File            38: C:\Users\frode\Desktop\Test folder
WINWORD.EXE        pid: 2780   type: File            40: C:\Users\frode\Desktop\Test folder
WINWORD.EXE        pid: 2780   type: File           6FC: C:\Users\frode\Desktop\Test folder\New Microsoft Word-dokument.docx

If you only want a yes/no answer you can use an if-test and -match to see it if returns any results.

if((.\handle64.exe /accepteula $path /nobanner) -match 'File') { "IN USE, ABORT MISSION!" }

Usually you're able to delete a folder even if explorer.exe is browsing inside it, so you could usually exclude that process from the results:

if((.\handle64.exe /accepteula $path /nobanner) -match 'File' -notmatch 'explorer.exe') { "IN USE, ABORT MISSION!" }
like image 127
Frode F. Avatar answered Sep 16 '25 08:09

Frode F.