Cannot remove item. The directory is not empty

HelloWorld picture HelloWorld · Jul 1, 2016 · Viewed 62k times · Source

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.

Answer

Richard picture Richard · Jul 1, 2016

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