I am trying to delete a folder with subfolders/files.
Remove-Item -Force -Recurse -Path $directoryPath
I am getting the error Cannot remove item. The directory is not empty.
My PowershellScript.ps1 has executionPolicy unrestricted. The root folder I try to delete with the current logged in user has full permission on this folder.
On my local pc the code works but not on my Windows Server 2012 R2
.
When this issue occurs, an error message appears that says “Cannot Delete foldername: The directory is not empty“. This problem can happen in Windows 10, 8, and 7. The problem can usually be solved with a Chkdsk scan.
Shutil rmtree() to Delete Non-Empty Directory The rmtree('path') deletes an entire directory tree (including subdirectories under it). The path must point to a directory (but not a symbolic link to a directory).
Open PowerShell by pressing the Start button and typing PowerShell. Press Enter. Type Remove-Item –path c:\testfolder –recurse and hit Enter. Please replace c:\testfolder with the full path to the folder you wish to delete.
Try cd into the directory, then remove all files using rm -rf * . Then try going out of the directory and use rmdir to delete the directory. If it still displays "Directory not empty" that means that the directory is being used. Try to close it or check which program is using it then re-use the command.
You could try the following:
Remove-Item -Force -Recurse -Path "$directoryPath\*"
Note when using the -Recurse
parameter with -Include
in Remove-Item
, it can be unreliable. So it's best to recurse the files first with Get-ChildItem
and then pipe into Remove-Item
. This may also help if you deleting large folder structures.
Get-ChildItem $directoryPath -Recurse | Remove-Item -Force
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