【问题标题】:Post-order Traverse in PowerShell recursePowerShell 递归中的后序遍历
【发布时间】:2019-02-27 07:03:00
【问题描述】:

Powershell 中的Get-ChildItem -Recurse 当前以级别顺序方式遍历目录。有没有办法在Powershell中以后序方式遍历目录?

我正在尝试删除超过特定时间的文件。删除文件后,如果子文件夹为空,也删除该文件夹。现在正在这样做。

$path = 'D:\Files'
Get-ChildItem -Path $path -Recurse | Where-Object {
(($_.LastWriteTime -lt (Get-Date).AddDays(-30)) -and ($_ -is [system.io.fileinfo]) )
} | Remove-Item 


Get-ChildItem -Path $path -Recurse | Where-Object {
($_ -is [System.IO.DirectoryInfo]) -and $_.CreationTime -lt (Get-Date).AddDays(-30) -and ((Get-ChildItem $_.FullName).Count -eq 0)
} | Remove-Item -Force

但我想在一个命令中完成。不像两个不同的命令。

【问题讨论】:

  • 编辑问题并详细解释您要做什么。一个实际的例子,即使是伪代码,也很好。
  • 你想达到什么目的才能从其他序列中受益?
  • 您真的想以相反的顺序查找项目,还是只是在常规get-childitem 选项之后重新排序?
  • 问题已更新。
  • 顺便说一句:在 PSv3+ 中,您可以分别使用 -File-Directory 将枚举限制为文件和目录。在包含这两种类型的枚举中,$_.PSIsContainer 可用于标识目录。

标签: powershell


【解决方案1】:

您可以将Get-ChildItem[Array]::Reverse 返回的项目的顺序颠倒

完整脚本:

$items = Get-ChildItem 'D:\Files' -Recurse
[Array]::Reverse($items)
$date = (Get-Date).AddDays(-30)
foreach ($item in $items) {
    if ($item.PSIsContainer) {
        if ($item.CreationTime -lt $date -and (Get-ChildItem $item.FullName).Count -eq 0) {
            Remove-Item $item.FullName
        }
    }
    elseif ($item.LastWriteTime -lt $date) {
        Remove-Item $item.FullName
    }
}

【讨论】:

  • 如果 Get-ChildItem 支持 -DepthFirst, -Postorder o 类似的就好了。
  • 这绝对不适合我 - 它应该是孩子,然后是直接父母,但对我来说,父母会在集合中稍后返回。
  • @user7660047 但这也是Get-ChildItem 的工作方式。它将首先列出所有直接子级,然后然后继续下一个最深的级别。如果您希望它与众不同,您可以轻松地为此编写自己的递归函数。
【解决方案2】:

我无法让邮政订单与 GCI 一起正常工作,有人声称应该这样做,但它并没有首先遍历深度。下面是使用 push directory 和 pop directory 命令的经典后排序算法的简单实现。将您的“操作”放在 Write-Host 所在的位置。

function PostOrder($d){
  pushd $d
  $folders = Get-ChildItem .\ -Directory -Force
  foreach ($folder in $folders){
    PostOrder($folder)
  }
  popd 
  Write-Host $d.FullName
}

PostOrder("C:\myFolder")

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
猜你喜欢
  • 2010-12-01
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
相关资源
最近更新 更多