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.
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!" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With