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.
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
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.
I was very nice to know about file locking and resolving through Powershell
LikeLiked by 1 person
Stay tuned for more awesome content !! 🙂
LikeLike
Nice find, this will go in my toolbox as soon as I’m on my Workstation.
But without testing this (and knowing not much about wmi) I assume 2 things:
1. On a local system this only shows processes running in my User context unless I launch an elevated PoSh console
2. On a remote system (say file server) this shows only files opened by processes running on said system and not for example the Notepad of John Smith from Accounting.
Are those assumptions correct?
Regards
Neo
LikeLiked by 1 person
I believe those assumptions are correct. However, its better to double check them once before proceeding on a production box. 🙂
LikeLike
Get-WmiObject Win32_Process | where {$_.commandLine -like “*$location*”} – this will not work if you trying to delete the folder and in that folder if you have opened Any Microsoft Office product. Commandline will not return the exact Path instead it will return some /dde…
Do you know any other alternative?
LikeLike
The “CommandLine” parameter will contain path to a lot of files that the Product will be using. Hence that command is strictly used only to pinpoint, which process is using that file and nothing else.
However, the different paths in “Command Line” will have a “space” as delimiter, you may want to parse that huge text to find out what other paths/files are accessed by that process/product.
LikeLike