PowerShell脚本需求:批量获取UNC目录总大小并导出错误到CSV
PowerShell 批量统计UNC目录总大小并导出错误
以下脚本可实现从CSV导入UNC路径列表,递归统计每个目录(含子目录)的总大小(单位:MB),同时捕获并记录错误信息,最终将结果导出到指定CSV文件。
脚本代码
# 配置输入输出路径 $inputCsvPath = "C:\path\to\your\input_paths.csv" $outputCsvPath = "C:\path\to\your\output_results.csv" # 导入路径列表(确保CSV包含名为`UNCPath`的列) $uncPaths = Import-Csv -Path $inputCsvPath # 初始化结果数组 $results = @() foreach ($path in $uncPaths) { $uncPath = $path.UNCPath.Trim() $resultObj = [PSCustomObject]@{ Path = $uncPath TotalSizeMB = $null ErrorMessage = $null } if ([string]::IsNullOrEmpty($uncPath)) { $resultObj.ErrorMessage = "路径为空" $results += $resultObj continue } try { # 递归获取所有文件并计算总大小,PowerShell 7+默认支持长路径,旧版需额外配置 $totalBytes = Get-ChildItem -LiteralPath $uncPath -File -Recurse -ErrorAction Stop | Measure-Object -Property Length -Sum | Select-Object -ExpandProperty Sum # 转换为MB并保留两位小数 $resultObj.TotalSizeMB = [math]::Round($totalBytes / 1MB, 2) } catch { # 捕获所有错误并记录详细信息 $resultObj.ErrorMessage = $_.Exception.Message } $results += $resultObj } # 导出结果到CSV $results | Export-Csv -Path $outputCsvPath -NoTypeInformation -Encoding UTF8
使用说明
- 输入CSV格式:确保输入CSV包含一列名为
UNCPath,每行是一个UNC路径(如\\fileserver1\share)。示例:UNCPath \\fileserver1\share \\fileserver2\docs - 权限要求:运行脚本的账号需拥有目标UNC目录的读取权限,否则会记录权限不足的错误。
- 长路径处理:若遇到路径过长错误,可使用PowerShell 7及以上版本(默认支持长路径),或在Windows中通过组策略/注册表启用长路径支持。
- 输出CSV:结果CSV包含三列:
Path(原UNC路径)、TotalSizeMB(总大小,单位MB,成功统计时为数值,失败时为null)、ErrorMessage(错误信息,无错误时为null)。
内容的提问来源于stack exchange,提问作者DuhMan
相关产品推荐
相关产品推荐

