Force Remove a Folder in-use using Powershell

Viewed 5308

I've created a script which at the end deletes all the associated files, self-destructs by deleting itself, and then it's supposed to delete the folder it is contained in as well.

I've tried several ways of closing Windows Explorer, searching through active processes and killing any related processes, but still cannot successfully delete the folder despite being able to self-destruct the script itself.

Set-Location -Path $PSScriptRoot

Remove-Item -Path $PSScriptRoot\Mobile -Force -Recurse

Remove-Item -Path $PSScriptRoot\NoMobile -Force -Recurse

Remove-Item -Path $MyInvocation.MyCommand.Source -Force -Recurse

Set-Location ..

Remove-Item $foldername -Force -Recurse

The last line throws an error that "The process cannot access the file...because it is being used by another process".

Any thoughts?

1 Answers

This may be not the answer you might be expecting right now but posting it so that it might be helpful if someone comes into this thread.

I happen to face issue in deleting the file then after help from co-worker I found that file was open in the editor or on some other user machine. I got to follow the below document to find out who had the file open and then close those files and tried to perform delete operation and this time it worked as expected. Please find the document to figure out who happen to have the file open which you are trying to delete.

https://techgoeasy.com/how-to-tell-who-has-a-file-open-in-windows/

Related