簡體   English   中英

僅返回包含使用 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,我想只返回包含以下文件的目錄:

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 -RecurseWhere-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM