3

I've seen on a lot of places (for example, here, here, or here) where people suggest to use

Get-ChildItem -Path "Some path" -Recurse | Remove-Item

to recursively delete a directory, but why would this work?

When I run Get-ChildItem -Path "foo" -Recurse | % { "$_" }, I see directories were listed first, and then files follows. It shows something like this:

1st_child_directory
2st_child_directory
...
1st_file_in_foo
2nd_file_in_foo
...
1st_file_in_1st_child_directory
2st_file_in_1st_child_directory
...
1st_file_in_2st_child_directory
...

And so on.

If these get piped into Remove-Item in the same order, then Remove-Item would remove directories first (which are still non-empty), and then remove files inside directories (but directories should already been removed), and this is a bit counter-intuitive... So why would Get-ChildItem -Recurse | Remove-Item work, and how does it work?

LanYi
  • 169
  • 3
  • 13
  • 1
    Your examples have either the `-Force` parameter applied or use an extension `*.csv` which folders rarely have. –  Dec 28 '18 at 00:31
  • You can find out: Create some sample directories and files and run the command, and see if it works or not. – Bill_Stewart Dec 28 '18 at 16:53

2 Answers2

1

To avoid a confirmation prompt, I had to use -recurse with remove-item:

get-childitem -recurse foo | remove-item -verbose -recurse

VERBOSE: Performing the operation "Remove Directory" on target "C:\users\admin\foo\dir1".
VERBOSE: Performing the operation "Remove File" on target "C:\users\admin\foo\dir1\file1".
VERBOSE: Performing the operation "Remove Directory" on target "C:\users\admin\foo\dir2".
VERBOSE: Performing the operation "Remove File" on target "C:\users\admin\foo\dir2\file2".
VERBOSE: Performing the operation "Remove Directory" on target "C:\users\admin\foo\dir3".
VERBOSE: Performing the operation "Remove File" on target "C:\users\admin\foo\dir3\file3".
js2010
  • 23,033
  • 6
  • 64
  • 66
0

It works when the directory "Some path" contains only files or empty sub directories.

At least some of the articles you linked to have been updated since to ensure that:

  • either the Get-ChildItem command returns only files
  • the option -Recurse was added to the Remove-Item command
Bram
  • 819
  • 1
  • 9
  • 24