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.
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
Every object in PowerShell has a Delete() method and you can use it to remove that object. To delete files and folders, use the Get-ChildItem command and use the Delete() method on the output.
Using PowerShell to Delete All Files Recursively If you need to also delete the files inside every sub-directory, you need to add the -Recurse switch to the Get-ChildItem cmdlet to get all files recursively.
Note that the answers given here for cmd (using rmdir , etc.) do not work in Powershell. Though Powershell does alias rmdir to Remove-Item (presumably with some switch; not sure which), it doesn't alias cmd-style switches like /s .
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.
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