[英]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,我想只返回包含以下文件的目录:
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
Pipe output 从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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.