Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot remove item. The directory is not empty

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.

like image 767
HelloWorld Avatar asked Jul 01 '16 09:07

HelloWorld


People also ask

Can't delete the directory is not empty?

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.

How do I delete a non-empty directory?

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).

How do I remove non-empty directory in PowerShell?

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.

Can not remove directory?

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.


1 Answers

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    
like image 91
Richard Avatar answered Sep 29 '22 09:09

Richard