Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 847
Matt Spradley Avatar asked Nov 17 '09 23:11

Matt Spradley


People also ask

How do you recursively delete a directory?

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.

How do I delete a directory in PowerShell?

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.

How do you recursively delete a file in PowerShell?

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.

Does Rmdir work in PowerShell?

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 .


1 Answers

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.

like image 68
Joey Avatar answered Oct 21 '22 21:10

Joey