【问题标题】:Why would Get-ChildItem -Recurse | Remove-Item work?为什么Get-ChildItem -Recurse |删除项目工作?
【发布时间】:2018-12-28 00:10:28
【问题描述】:

我在很多地方(例如,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 会起作用,它是如何起作用的呢?

【问题讨论】:

  • 您的示例要么应用了-Force 参数,要么使用了文件夹很少有的扩展名*.csv
  • 你可以发现:创建一些示例目录和文件并运行命令,看看它是否有效。

标签: powershell get-childitem


【解决方案1】:

当目录“某些路径”只包含文件或空子目录时,它可以工作。

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

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

【讨论】:

    【解决方案2】:

    为避免出现确认提示,我不得不将 -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".
    

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 2012-06-03
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多