【问题标题】:Ignoring subdirectories in powershell忽略powershell中的子目录
【发布时间】:2020-04-25 15:06:14
【问题描述】:

我有一行代码打印出所有类似于 $filename 的文件和文件夹,例如关键字“abc”还将包含一个文件/文件夹“abcdef”

Get-ChildItem -Path 'C:\' -Filter $filename -Recurse | %{$_.FullName}

我想这样做,以便搜索这些文件不会进入文件夹的子目录

例如名为“abc”的文件夹和子文件夹“abcdef”只打印出“C:\abc”

目前这行代码会打印出“C:\abc”和“C:\abc\abcdef”

最好的方法是什么?

【问题讨论】:

  • 你试过删除-Recurse吗?
  • @Glenn,是的,我试过了,虽然它确实解决了这个问题,但它带来了另一个问题。从上面的例子开始,如果有一个文件夹“C:\test”包含一个名为“abc”的文件夹(位置是 C:\test\abc),它也会忽略它。我只想在它进入其子目录之前获取此类文件夹的第一个实例。

标签: powershell file directory subdirectory


【解决方案1】:

这样就可以了。

Get-ChildItem 在顶层执行以填充处理队列 ($ProcessingQueue)

然后,将运行一个循环,直到处理队列中没有任何剩余元素。 队列中的每个元素都会经历相同的过程。

要么匹配过滤器,在这种情况下,它将被添加到$Result 变量中,或者不匹配,在这种情况下,Get-ChildItem 将在该目录上被调用,并将其结果附加到队列中。

这确保我们一旦找到匹配项就不会再处理任何目录树,并且仅当目录与文件夹不匹配时才会应用递归。

--

Function Get-TopChildItem($Path, $Filter) {
        $Results = [System.Collections.Generic.List[String]]::New()
        $ProcessingQueue = [System.Collections.Queue]::new()

        ForEach ($item in (Get-ChildItem -Directory $Path)) {
            $ProcessingQueue.Enqueue($item.FullName) 
        }    

        While ($ProcessingQueue.Count -gt 0) {
                $Item = $ProcessingQueue.Dequeue()

                if ($Item -match $Filter) {
                        $Results.Add($Item) 
                }
                else {
                        ForEach ($el in (Get-ChildItem -Path $Item -Directory)) {
                                $ProcessingQueue.Enqueue($el.FullName) 
                        }
                }
        }
        return $Results
}

#Example
Get-TopChildItem -Path "C:\_\111" -Filter 'obj'

【讨论】:

  • 非常感谢。我现在理解了它的逻辑,但我遇到了一些错误。抱歉,如果它们微不足道,我是新手。 + ForEach-Object($item in (Get-ChildItem -Directory $Path)){$Proces ... + ~~ 表达式或语句中出现意外标记“in”。 + ForEach-Object($item in (Get-ChildItem -Directory $Path)){$Proces ... + ~ Missing closing ')' in expression. + Function Get-TopChildItem($Path, $Filter) { + ~ Missing closing '}' in statement block or type definition.
  • 啊,糟糕... ForEach-Object 需要替换为 ForEach。我最初使用管道发布了我的答案,但随后在没有测试的情况下进行了编辑,我编辑了我的答案。再试一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多