[英]List file count by subfolder
我正在尝试使用 powershell 生成文件夹名称列表以及每个文件夹中有多少文件。
我有这个脚本
$dir = "C:\Users\folder"
Get-ChildItem $dir -Recurse -Directory | ForEach-Object{
[pscustomobject]@{
Folder = $_.FullName
Count = @(Get-ChildItem -Path $_.Fullname -File).Count
}
} | Select-Object Folder,Count
其中列出了文件计数,但它放置了完整路径(即C:\\Users\\name\\Desktop\\1\\2\\-movi...
)。 有没有办法只显示最后一个文件夹(“电影”)并将结果保存到 .txt 文件中?
谢谢
而不是$_.FullName
,使用$_.Name
只获取目录名称。
您的Select-Object
调用是多余的 - 它实际上是一个空操作。
例如,虽然很容易将结果发送到带有>
的.txt
文件,但最好使用更结构化的格式进行以后的编程处理。 在最简单的形式中,这意味着通过Export-Csv
输出到 CSV 文件; 然而,通常,将对象序列化为文件的最Export-CliXml
是使用Export-CliXml
。
使用Export-Csv
进行序列化:
$dir = 'C:\Users\folder'
Get-ChildItem -LiteralPath $dir -Recurse -Directory | ForEach-Object {
[pscustomobject] @{
Folder = $_.Name
Count = @(Get-ChildItem -LiteralPath $_.Fullname -File).Count
}
} | Export-Csv -NoTypeInformation results.csv
请注意,您可以通过将ForEach-Object
调用替换为使用计算属性的Select-Object
调用来简化命令:
$dir = 'C:\Users\folder'
Get-ChildItem -LiteralPath $dir -Recurse -Directory |
Select-Object Name,
@{ n='Count'; e={@(Get-ChildItem -LiteralPath $_.Fullname -File).Count} } |
Export-Csv -NoTypeInformation results.csv
你的意思是这样的......
Clear-Host
Get-ChildItem -Path 'd:\temp' -Recurse -Directory |
Select-Object Name,FullName,
@{Name='FileCount';Expression = {(Get-ChildItem -Path $_.FullName -File -Recurse| Measure-Object).Count}} `
| Format-Table -AutoSize
# Results
Name FullName FileCount
---- -------- ---------
abcpath0 D:\temp\abcpath0 5
abcpath1 D:\temp\abcpath1 5
abcpath2 D:\temp\abcpath2 5
Duplicates D:\temp\Duplicates 12677
EmptyFolder D:\temp\EmptyFolder 0
NewFiles D:\temp\NewFiles 4
PngFiles D:\temp\PngFiles 4
results D:\temp\results 905
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.