代码如下很实用
powershellGet-ChildItem C:\ -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.Length -gt 100MB } | Sort-Object Length -Descending | Select-Object Name, @{Name="Size(MB)";Expression={[math]::Round($_.Length/1MB,2)}}, FullName | Export-Csv E:\bigfiles.csv -NoTypeInformation -Encoding UTF8
以下是自定义路径和代码,另存为ps1文件注意utf8带签名
powershell# 切换到UTF-8编码 chcp 65001 > $null do { $pathInput = Read-Host "请输入要扫描的路径 (例如 C:\Users)" $path = [System.IO.Path]::GetFullPath($pathInput.Trim()) $validPath = Test-Path $path if (-not $validPath) { Write-Host "路径不存在!请输入有效路径。" -ForegroundColor Red } } while (-not $validPath) do { $sizeMB = Read-Host "请输入要过滤的最小文件大小 (单位MB,例如 100)" $validInput = [int]::TryParse($sizeMB, [ref]$null) -and [int]$sizeMB -ge 0 if (-not $validInput) { Write-Host "请输入有效的非负数!" -ForegroundColor Red } } while (-not $validInput) $sizeBytes = [int]$sizeMB * 1048576 $bigFiles = Get-ChildItem $path -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.Length -gt $sizeBytes } | Sort-Object Length -Descending | Select-Object Name, @{Name="Size(MB)";Expression={[math]::Round($_.Length/1MB,2)}}, FullName if ($bigFiles) { Write-Host "在 $path 中找到大文件:" -ForegroundColor Green $bigFiles | Format-List $bigFiles | Export-Csv E:\bigfiles.csv -NoTypeInformation -Encoding UTF8 Write-Host "CSV 已保存到 E:\bigfiles.csv" -ForegroundColor Green } else { Write-Host "在 $path 中未找到大于 $sizeMB MB 的文件" -ForegroundColor Yellow }
以下是同等功能的Python代码,效率比Powershell低一些
pythonimport os
import csv
from pathlib import Path
def get_valid_path():
"""提示用户输入路径并校验"""
while True:
path = input("请输入要扫描的路径(例如 C:\\Users):").strip()
# 规范化路径(支持斜杠、反斜杠)
path = str(Path(path).resolve())
if os.path.exists(path):
return path
print("\033[91m路径不存在!请输入有效路径。\033[0m")
def get_valid_size():
"""提示用户输入文件大小并校验"""
while True:
size_mb = input("请输入要过滤的最小文件大小(单位MB,例如 100):").strip()
try:
size_mb = float(size_mb)
if size_mb >= 0:
return size_mb
print("\033[91m请输入有效的非负数!\033[0m")
except ValueError:
print("\033[91m请输入有效的非负数!\033[0m")
def scan_big_files(path, size_mb):
"""扫描大于指定大小的文件"""
size_bytes = int(size_mb * 1024 * 1024) # MB转字节
big_files = []
# 递归扫描
for root, _, files in os.walk(path, onerror=lambda e: None):
for file in files:
file_path = os.path.join(root, file)
try:
file_size = os.path.getsize(file_path)
if file_size > size_bytes:
big_files.append({
"Name": file,
"Size(MB)": round(file_size / (1024 * 1024), 2),
"FullName": file_path
})
except (OSError, PermissionError):
continue # 跳过无权限或坏文件
# 按大小降序排序
return sorted(big_files, key=lambda x: x["Size(MB)"], reverse=True)
def main():
# 获取输入
path = get_valid_path()
size_mb = get_valid_size()
# 扫描
big_files = scan_big_files(path, size_mb)
# 输出结果
if big_files:
print("\033[92m在 {} 中找到大文件:\033[0m".format(path))
# 屏幕打印
for file in big_files:
print(f"Name : {file['Name']}")
print(f"Size(MB) : {file['Size(MB)']}")
print(f"FullName : {file['FullName']}")
print()
# 生成CSV
csv_file = "E:\\bigfiles.csv"
with open(csv_file, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=["Name", "Size(MB)", "FullName"])
writer.writeheader()
writer.writerows(big_files)
print("\033[92mCSV 已保存到 {}\033[0m".format(csv_file))
else:
print("\033[93m在 {} 中未找到大于 {} MB 的文件\033[0m".format(path, size_mb))
if __name__ == "__main__":
main()
本文作者:ivan
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!