PowerShell扫描文件夹大小
本帖最后由 LiuJiaCheng11 于 2024-8-8 12:20 编辑某天我发现我的E盘快满了,想清理一些大文件,但又不想去网上下载什么工具,就自己整个脚本去扫描了
效果图1
效果图2
有个无权限的文件夹,扫不了会报错(但似乎文件大小是正确的),报错信息会在进度条完成,输出结果后,再输出有错误的文件信息
代码
function Get-ResolvePath {
param (
$Path
)
$ResolvePath = Resolve-Path -Path $Path
return $ResolvePath
}
function Get-FolderSize {
param (
$FolderPath
)
$FolderPath = Get-ResolvePath $FolderPath
if (Test-Path -Path $FolderPath -PathType Leaf) {
# 如果路径是文件,则直接返回文件大小
$file = Get-Item -Path $FolderPath -Force
return $file.Length
}
$folderSize = 0
try {
Get-ChildItem -Recurse -File -Path $FolderPath -Force -ErrorAction Stop | ForEach-Object {
try {
$folderSize += $_.Length
} catch {
$global:errors += "处理文件时出错: $($_.FullName) - 错误信息: $($_.Exception.Message)"
}
}
} catch {
$global:errors += "解析目录时出错: $FolderPath - 错误信息: $($_.Exception.Message)"
}
return $folderSize
}
do {
# 初始化错误数组
$global:errors = @()
# 读取用户输入的文件夹路径
$folderPath = Read-Host "请输入文件夹路径(空表示当前路径)"
if ($folderPath -eq ""){
$folderPath = $PWD.Path
}
$subFolders = Get-ChildItem -Path $folderPath -Force
$totalFolders = $subFolders.Count
$currentFolder = 0
$sortedFolders = $subFolders | ForEach-Object {
$currentFolder++
$progressPercent = ::Round(($currentFolder / $totalFolders) * 100, 2)
# 更新进度条
Write-Progress -Activity "正在处理目录" -Status "$($_.FullName)" -PercentComplete $progressPercent
# 获取文件夹的大小
$folderSize = Get-FolderSize -FolderPath $_.FullName
@{
FolderName = $_.Name
FolderSize = $folderSize
}
} | Sort-Object -Property FolderSize -Descending
# 进度条完成
Write-Progress -Activity "处理完成" -Status "所有目录已处理" -Completed
# 显示文件夹名称和大小
$sortedFolders | ForEach-Object {
if (!::IsNullOrEmpty($_.FolderName)) {
if ($_.FolderSize -ge 1GB) {
$formattedSize = "{0:N2} GB" -f ($_.FolderSize / 1GB)
} else {
if ($_.FolderSize -ge 1MB) {
$formattedSize = "{0:N2} MB" -f ($_.FolderSize / 1MB)
} else {
$formattedSize = "{0:N2} KB" -f ($_.FolderSize / 1KB)
}
}
Write-Host "$($formattedSize) - $($_.FolderName)"
}
}
# 输出错误信息
if ($global:errors.Count -gt 0) {
Write-Host "处理过程中出现以下错误:" -ForegroundColor Red
$global:errors | ForEach-Object { Write-Host $_ -ForegroundColor Red }
}
$continue = Read-Host "是否继续循环?(Y/N)"
} while ($continue -eq "Y" -or $continue -eq "y")
本帖最后由 LiuJiaCheng11 于 2024-8-8 12:18 编辑
最大的居然是微信文件夹
页:
[1]