Lets face it, we all have been in that weird situation, where we want to delete a folder and we get a prompt saying – “The action can’t be completed because the file is open in another program”. If we are aware of such a program (process), that is using our file, then we can just go and kill that process.

But what if we have 100s of files in that folder and multiple processes running? How do we pin point the culprit process that is using the random file, under the folder that we are trying to delete.

I know that there are a few third-party software’s that are available to solve this issue. Since we are Powershell Lovers, lets solve this problem the Powershell way.

In my demonstration, I have a text document called “demo.txt” under the folder, “E:\Work\Powershell\scripts\demo”. Now, I open that file using a notepad. When I try to delete the folder “demo”, I will get the below warning.

cant delete

To solve this problem, we can query the Win32_Process WMI class to find out the culprit process that is using our file.

Run the below cmdlet:

$location = 'E:\Work\Powershell\scripts\demo'
Get-WmiObject Win32_Process | where {$_.commandLine -like "*$location*"} | select name

gotyou

From the screen shot, you can see that we accurately spotted that the “notepad.exe” process was using our file. We can now terminate the process and then proceed in deleting the file.

This cmdlet can be used as a template or as a starting phase to develop more complicated logic/script accordingly.

 

Advertisements