Get-ChildItem 和文件统计 Get-ChildItem 基本用法-Force 参数的作用在日常系统管理和文件整理工作中,我们经常需要统计某个目录(及其子目录)的占用空间。PowerShell 提供了强大的文件遍历和计算能力,但默认情况下,它不会处理隐藏文件或系统文件。本文将详细介绍如何使用 PowerShell 递归计算文件夹大小,并确保包含隐藏文件。
Get-ChildItem 和文件统计Get-ChildItem 基本用法Get-ChildItem(别名 dir 或 ls)是 PowerShell 中用于列出文件和目录的核心命令。基本语法:
Get-ChildItem -Path "C:\TargetFolder"-Path:指定目标路径(默认当前目录)-Directory:仅返回目录-File:仅返回文件-Recurse:递归遍历子目录要计算文件夹大小,我们需要:
Length 属性)示例:计算单个文件夹大小
$folderPath = "C:\Example"
$files = Get-ChildItem -Path $folderPath -Recurse -File
$totalSize = ($files | Measure-Object -Property Length -Sum).Sum / 1MB
Write-Host "Total Size: $($totalSize.ToString('0.00')) MB"Measure-Object -Sum 计算总和/ 1MB 转换为 MB(1MB = 1024 * 1024 字节)Hidden 属性(如 .git 目录)。pagefile.sys)。默认情况下,Get-ChildItem 不会返回隐藏或系统文件。
-Force 参数的作用-Force 参数让 Get-ChildItem 返回 所有 文件,包括:
示例:列出所有文件(含隐藏文件)
Get-ChildItem -Force最初的脚本仅计算非隐藏目录和文件:
Get-ChildItem -Directory | ForEach-Object {
$size = (Get-ChildItem -Path $_.FullName -Recurse -File | Measure-Object -Property Length -Sum).Sum / 1MB
[PSCustomObject]@{
Folder = $_.Name
Size_MB = [math]::Round($size, 2)
}
} | Sort-Object Size_MB -Descending问题:
AppData).gitignore)添加 -Force 参数,确保包含隐藏文件:
Get-ChildItem -Directory -Force | ForEach-Object {
$size = (Get-ChildItem -Path $_.FullName -Recurse -File -Force | Measure-Object -Property Length -Sum).Sum / 1MB
[PSCustomObject]@{
Folder = $_.Name
Size_MB = [math]::Round($size, 2)
}
} | Sort-Object Size_MB -Descending改进点:
Get-ChildItem -Directory -Force:包含隐藏目录Get-ChildItem -Recurse -File -Force:递归计算所有文件(含隐藏文件)ForEach-Object -Parallel,需 PowerShell 7+)。-Depth 参数(如 -Depth 3 仅遍历 3 层子目录)。C:\Windows)需要管理员权限才能访问。-ErrorAction SilentlyContinue 忽略无权限访问的目录。优化后的脚本(带错误处理)
Get-ChildItem -Directory -Force -ErrorAction SilentlyContinue | ForEach-Object {
$size = (Get-ChildItem -Path $_.FullName -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum / 1MB
[PSCustomObject]@{
Folder = $_.Name
Size_MB = [math]::Round($size, 2)
}
} | Sort-Object Size_MB -Descending# 计算当前目录下所有文件夹大小(含隐藏文件)
$results = Get-ChildItem -Directory -Force -ErrorAction SilentlyContinue | ForEach-Object {
$size = (Get-ChildItem -Path $_.FullName -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum).Sum / 1MB
[PSCustomObject]@{
Folder = $_.Name
Size_MB = [math]::Round($size, 2)
}
} | Sort-Object Size_MB -Descending
# 输出结果
$results | Format-Table -AutoSize
# 可选:导出到 CSV
$results | Export-Csv -Path "FolderSizes.csv" -NoTypeInformationGet-ChildItem -Force 是统计隐藏文件的关键。通过本文的优化方法,您可以更准确地计算文件夹大小,适用于磁盘清理、日志分析等场景。
进一步优化方向:
Robocopy 进行快速统计(适用于超大型目录)希望本文对您的 PowerShell 脚本编写有所帮助! 🚀