views:

1121

answers:

2

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 and 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.

+8  A: 
Remove-Item -Recurse -Force some_dir

does indeed work as advertised here.

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.

Joey
I think you are correct.I was getting a "Cannot remove the item at 'some directory' because it is in use." error and assumed it was an issue with the recursion algorithm and went searching for a workaround.It turns out I had a process I fired off earlier in the script that was working in the target directory. When changed the script to wait for the other process the "Remove-Item -Recurse -Force" command works.Always look in the mirror first:)
Matt Spradley
+2  A: 

How about the old-school dos command: rd /s

Anonymous
Would have to be `cmd /c "rd /s"` ...
Joey