PowerShell如何为已有CSV文件添加新列?
PowerShell 实现CSV追加统计列的脚本
以下是直接可用的代码,实现每次运行时新增以当前时间为表头的文件数统计列:
# 定义CSV文件路径(脚本所在目录下的FolderFileStats.csv) $csvPath = Join-Path $PSScriptRoot "FolderFileStats.csv" # 获取当前时间作为列名(格式化避免特殊字符) $currentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" # 统计当前目录下所有子文件夹的文件数量 $folderStats = Get-ChildItem -Directory | ForEach-Object { [PSCustomObject]@{ FolderName = $_.Name $currentDate = (Get-ChildItem -Path $_.FullName -File | Measure-Object).Count } } # 处理CSV文件 if (Test-Path $csvPath) { # 读取现有CSV数据 $existingData = Import-Csv -Path $csvPath # 合并新统计数据与现有数据 $mergedData = foreach ($folder in $existingData) { # 查找当前文件夹的新统计值 $newStat = $folderStats | Where-Object { $_.FolderName -eq $folder.FolderName } # 添加新列数据 $folder | Add-Member -MemberType NoteProperty -Name $currentDate -Value $newStat.$currentDate -Force $folder } # 检查是否有新增的文件夹(现有CSV中没有的) $newFolders = $folderStats | Where-Object { $_.FolderName -notin $existingData.FolderName } if ($newFolders) { $mergedData += $newFolders } # 导出合并后的数据,覆盖原有CSV $mergedData | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8 } else { # 首次运行,直接导出统计数据 $folderStats | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8 }
关键说明:
- 列名格式化:用
yyyy-MM-dd HH:mm:ss格式的时间作为列名,避免因特殊字符导致CSV解析错误 - 数据合并逻辑:
- 读取现有CSV后,通过
FolderName匹配,为每一行添加新的统计列 - 自动识别新增的子文件夹,将其追加到CSV末尾
- 读取现有CSV后,通过
- 避免空行问题:通过
Add-Member直接在现有对象上添加属性,而非盲目追加行,解决了重复运行时出现空行的问题 - 编码设置:指定
-Encoding UTF8确保CSV在不同环境下的兼容性
内容的提问来源于stack exchange,提问作者tnpir4002
相关产品推荐
相关产品推荐

