为什么要使用Get-ChildItem -Recurse |移除项目吗?

时间:2018-12-28 00:10:28

标签: powershell get-childitem

我见过很多建议使用的地方(例如hereherehere

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

以递归方式删除目录,但是为什么这样做有效?

运行Get-ChildItem -Path "foo" -Recurse | % { "$_" }时,我看到目录首先列出,然后是文件。 它显示如下内容:

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

以此类推。

如果这些文件以相同的顺序传递到Remove-Item中,则Remove-Item将首先删除目录(仍然是非空的),然后删除目录中的文件(但是目录应该已经被删除了) ),这有点违反直觉... 那么Get-ChildItem -Recurse | Remove-Item为什么会起作用,又如何起作用?

2 个答案:

答案 0 :(得分:0)

当目录“Some path”只包含文件或空子目录时有效。

至少您链接到的一些文章已经更新,以确保:

  • Get-ChildItem 命令只返回文件
  • 选项 -Recurse 已添加到 Remove-Item 命令

答案 1 :(得分:0)

为了避免出现确认提示,我不得不将 -recurse 与 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".
相关问题