You are 100% correct - this isn’t a great outcome. We can definitely look into this a bit further to work out what’s going on.
Additional to the information previously discussed, another thought crossed my mind regarding recursive deleting of larger file/folder structures on a windows environment. I have heard that Powershell can in fact fail when attempting to recursively delete files/folders on Windows systems, in short because windows runs the operations asynchronously. This may in fact show similar traits as what you are seeing.
A simple example of the issue is this:
- Does folder A/B/C Exist? Yes
- Send command to delete A/B/C
- Does folder A/B/D Exist? Yes
- Send command to delete A/B/D (This command gets caught on a busy thread)
- A/B/C gets deleted
- Should A/B be empty? Yes
- Send command to delete A/B
- Command A/B tries to delete but is in use due to the delete A/B/D command still not executing.
So the above issue and as well as other legitimately open file handles need to be addressed. One suggestion to deal with this is by finding the deepest child-path and removing the files using the -force command, then remove the folder that they were in, then again find the next deepest child path.
There is a lot of information out on google around this issue - but I found this discussion thread to be the most helpful for me: https://github.com/PowerShell/PowerShell/issues/8211
Please, let me know if you need a hand to develop a script that works in your situation.
Hopefully this is more of a satisfactory answer for you.