假設我有一個目錄樹,如下所示:
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 執行此操作的最佳方法是什么?
uj5u.com熱心網友回復:
將輸出從Get-ChildItem -Directory -Recurseto管道傳輸Where-Object并測驗每個檔案下是否存在任何檔案:
Get-ChildItem -Directory -Recurse |Where-Object { $_ |Get-ChildItem -File |Select -First 1 }
uj5u.com熱心網友回復:
從您要測驗的任何根檔案夾中,您都可以通過以下方式獲取檔案所在的所有目錄:
$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
uj5u.com熱心網友回復:
我剛剛測驗了這個。請注意,通常人們會先嘗試編碼,然后就代碼中的錯誤獲得幫助...
試試下面的
$a = Get-ChildItem -Recurse -File *.txt | sort Count -Descending
$a | Select Name, BaseName, Directory, DirectoryName
如果要從中選擇更多查看 - System.IO.FileInfo
$a | get-member
uj5u.com熱心網友回復:
另一種方法...這將獲取所有目錄的串列,然后檢查每個目錄是否包含檔案。
Get-ChildItem -Directory -Recurse -Path 'C:\' |
ForEach-Object { if ((Get-ChildItem -File -Path $_).Length -gt 0) { $_.FullName }}
uj5u.com熱心網友回復:
已經提出的答案的另一種選擇:
[System.Collections.Generic.HashSet[string]]::new(
[string[]](Get-ChildItem . -Recurse -Filter *.txt).Directory
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/375395.html
上一篇:如何使用C替換文本檔案中的字符?
