Return 仅包含使用 Powershell 的文件的文件夹

Return only folders containing files using Powershell

假设我有一个目录树如下:

root
├───A
│   ├───1
│   │       a.txt
│   │       b.txt
│   │
│   ├───2
│   │       a.txt
│   │
│   └───3
├───B
│   ├───1
│   │       a.txt
│   │       b.txt
│   │
│   └───3
└───C
    ├───1
    └───2

使用 Powershell,我想 return 仅包含如下文件的目录:

root/A/1
root/A/2
root/B/1

使用 Powershell 执行此操作的最佳方法是什么?

无论您要测试什么根文件夹,您都可以通过以下方式获取文件存在的所有目录:

$path = "path you wish to evaluate"
#recurse all directories under $path, 
#returning directories where there is a leaf child item below it
Get-ChildItem $path -Directory -Recurse | 
  Where-Object { Test-Path "$_\*" -PathType Leaf } |
  Select FullName

我刚刚测试了这个。请注意,通常人们会先尝试编写代码,然后在代码中出现错误时寻求帮助...

试试下面的方法

$a = Get-ChildItem -Recurse -File *.txt  | sort Count -Descending
$a | Select Name, BaseName, Directory, DirectoryName

如果您想 select 查看更多来自 - System.IO.FileInfo

$a | get-member

Get-ChildItem -Directory -Recurse 的输出通过管道传输到 Where-Object 并测试每个文件下是否存在任何文件:

Get-ChildItem -Directory -Recurse |Where-Object { $_ |Get-ChildItem -File |Select -First 1 }

另一种方法...获取所有目录的列表,然后检查每个目录是否包含文件。

Get-ChildItem -Directory -Recurse -Path 'C:\' |
    ForEach-Object { if ((Get-ChildItem -File -Path $_).Length -gt 0) { $_.FullName }}

已提出答案的另一种选择:

[System.Collections.Generic.HashSet[string]]::new(
    [string[]](Get-ChildItem . -Recurse -Filter *.txt).Directory
)