How to recursively delete an entire directory with PowerShell 2.0?
What is the simplest way to forcefully delete a directory and all its subdirectories in PowerShell? I am using PowerShell V2 in Windows 7.
I have learned from several sources that the most obvious command, Remove-Item $targetDir -Recurse -Force
, does not work correctly. This includes a statement in the PowerShell V2 online help (found using Get-Help Remove-Item -Examples
) that states:
...Because the Recurse parameter in this cmdlet is faulty, the command uses the Get-Childitem cmdlet to get the desired files, and it uses the pipeline operator to pass them to the Remove-Item cmdlet...
I have seen various examples that use Get-ChildItem and pipe it to Remove-Item , but the examples usually remove some set of files based on a filter, not the entire directory.
I am looking for the cleanest way to blow out an entire directory, files and child directories, without generating any user warning messages using the least amount of code. A one-liner would be nice if it is easy to understand.
Remove-Item -Recurse -Force some_dir
does indeed work as advertised here.
rm -r -fo some_dir
are shorthand aliases that work too.
As far as I understood it, the -Recurse
parameter just doesn't work correctly when you try deleting a filtered set of files recursively. For killing a single dir and everything below it seems to work fine.
I used:
rm -r folderToDelete
This works for me like a charm (I stole it from Ubuntu).
When deleting files recursively using a simple Remove-Item "folder" -Recurse
I sometimes see an intermittent error : [folder] cannot be removed because it is not empty.
This answer attempts to prevent that error by individually deleting the files.
function Get-Tree($Path,$Include='*') {
@(Get-Item $Path -Include $Include -Force) +
(Get-ChildItem $Path -Recurse -Include $Include -Force) |
sort pspath -Descending -unique
}
function Remove-Tree($Path,$Include='*') {
Get-Tree $Path $Include | Remove-Item -force -recurse
}
Remove-Tree some_dir
An important detail is the sorting of all the items with pspath -Descending
so that the leaves are deleted before the roots. The sorting is done on the pspath
parameter since that has more chance of working for providers other than the file system. The -Include
parameter is just a convenience if you want to filter the items to delete.
It's split into two functions since I find it useful to see what I'm about to delete by running
Get-Tree some_dir | select fullname
链接地址: http://www.djcxy.com/p/29104.html