有这样一个需求,需要知道当前目录及子目录下的文件数量,并给数量加上括号,再将统计结果生成txt文本文件“目录文件统计结果.txt”。
=== 一级子目录文件数量统计(2025-12-22 15:30:25) ===
统计根目录:D:\test_folder
文档资料 (128)
图片素材 (456)
系统文件夹 (无访问权限)
测试目录 (0)
将以下代码中的$rootPath = “D:\test_folder”替换为你所要统计的目录。按 Win + R 输入 powershell 打开窗口,复制以下代码粘贴运行。
<#
功能:统计指定目录下一级子目录的名称+所有层级文件总数,结果输出到控制台+文本文件
格式:目录名 (文件数量)
兼容:支持所有Windows PowerShell版本(解决-Path参数报错问题)
#>
# 设置要统计的根目录路径(替换为你的实际路径)
$rootPath = "D:\test_folder" # 示例:C:\Users\你的用户名\Desktop
# 强制设置控制台编码为UTF-8,解决中文乱码
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# 定义输出的文本文件路径(在主目录下)
$outputFile = Join-Path -Path $rootPath -ChildPath "目录文件统计结果.txt"
try {
# 清空原有文件(避免追加旧内容)
if (Test-Path $outputFile) {
Remove-Item $outputFile -Force
}
# 检查根目录是否存在
if (-not (Test-Path $rootPath -PathType Container)) {
Write-Host "`n❌ 错误:目录 '$rootPath' 不存在!" -ForegroundColor Red
Read-Host "`n按任意键退出..."
exit 1
}
# 输出统计标题(控制台)
Write-Host "`n=== 一级子目录及下属所有文件数量统计(递归) ===" -ForegroundColor Green
Write-Host "📌 统计根目录:$rootPath`n" -ForegroundColor Cyan
Write-Host "📄 结果将保存到:$outputFile`n" -ForegroundColor Cyan
# 写入文本文件的标题(移除-Path参数,直接传文件路径,兼容低版本PowerShell)
"=== 一级子目录文件数量统计($(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')) ===" | Out-File $outputFile -Encoding utf8
"统计根目录:$rootPath`n" | Out-File $outputFile -Encoding utf8 -Append
# 获取根目录下所有一级子目录
$subDirs = Get-ChildItem $rootPath -Directory -Force -ErrorAction Stop
# 判断是否有一级子目录
if ($subDirs.Count -eq 0) {
$noDirMsg = "未找到任何一级子目录!"
Write-Host "⚠️ $noDirMsg`n" -ForegroundColor Yellow
$noDirMsg | Out-File $outputFile -Encoding utf8 -Append
}
else {
# 遍历每个一级子目录,递归统计文件数量
foreach ($dir in $subDirs) {
try {
# 递归统计所有文件
$allFiles = Get-ChildItem $dir.FullName -File -Recurse -Force -ErrorAction Stop
$fileCount = $allFiles.Count
# 格式化输出内容(目录名 (数量))
$outputLine = "$($dir.Name) ($fileCount)"
# 输出到控制台
Write-Host $outputLine -ForegroundColor White
# 追加到文本文件(移除-Path参数)
$outputLine | Out-File $outputFile -Encoding utf8 -Append
}
catch [System.UnauthorizedAccessException] {
# 权限不足的情况
$outputLine = "$($dir.Name) (无访问权限)"
Write-Host $outputLine -ForegroundColor Red
$outputLine | Out-File $outputFile -Encoding utf8 -Append
}
catch {
# 其他异常
$outputLine = "$($dir.Name) (统计失败:$($_.Exception.Message))"
Write-Host $outputLine -ForegroundColor Red
$outputLine | Out-File $outputFile -Encoding utf8 -Append
}
}
}
Write-Host "`n✅ 统计完成!结果已保存到文本文件`n" -ForegroundColor Green
}
catch {
# 捕获全局异常(移除-Path参数)
Write-Host "`n❌ 程序运行出错:$($_.Exception.Message)" -ForegroundColor Red
"程序运行出错:$($_.Exception.Message)" | Out-File $outputFile -Encoding utf8 -Append
}
finally {
# 强制暂停,防止窗口自动退出
Read-Host "`n按任意键退出..."
}
席天卷地个人博客

评论前必须登录!
注册