Reputation: 29866
In PowerShell, I believe I'm observing that PowerShell is attempting to delete folders before their contents are deleted. The command I'm using is Remove-Item
.
In the past, using it with -recurse
would sporadically error out complaining about the directory not being empty. When I saw that error, I would find the target directory empty when I went to check. My best guess is that it was moving on while files were still in the process of being deleted. Now I'm seeing more evidence of that.
Because of the above, I was trying to use the following snippet:
$toDelete = Get-ChildItem $path -Recurse
[Array]::Reverse($toDelete)
$toDelete | Remove-Item
Remove-Item $path
What I'm getting now is the following prompt:
Confirm
The item at [path to directory] has children and the Recurse parameter was not specified. If you continue, all
children will be removed with the item. Are you sure you want to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
Again, the directory is empty when I go check it. My best guess is that $toDelete | Remove-Item
is returning before the files are actually deleted and that I'm seeing this prompt on Remove-Item $path
.
Is this a known issue? Are my suspicions about what's happening wrong? How can I work around it?
I tried using cmd /C "rd /S [path to directory]"
, but this was problematic because I found exit code was 0
when it failed to delete some children that were in use. (That is a potential situation for my usage, and I need it to be an error situation.)
Upvotes: 3
Views: 1039
Reputation: 68263
Remove-Item with the -Recurse switch was buggy in V1-V3 (it actually tells you it doesn't work properly in the Help). It was fixed (finally) in V4. I've used this method as a workaround and it's always worked for me:
$toDelete = Get-ChildItem $path -Recurse |
select -ExpandProperty fullname |
sort -Property Length -Descending |
Remove-Item
Remove-Item $path
Upvotes: 3