PowerShell中如何将另一变量输出追加到已有CSV的已用列后
问题描述
我正在编写脚本,用于在两台服务器间复制文件夹及子文件夹(每个文件夹包含多个文件)。目前已实现对比源服务器(Server1)与目标服务器(Server2)的文件夹名称及各文件夹内文件数量的功能,当前代码可将$PRODFLDFileCount的输出写入CSV,但需要将$COBFLDFileCount的输出追加到同一CSV文件的已用列范围之后,让两边的文件夹信息和计数并列展示。
现有代码
PROD服务器文件夹及文件计数代码
$PRODFLDFileCount = Get-ChildItem -LiteralPath $SRCLPRODCAS -Directory | ForEach-Object { [pscustomobject] @{ 'Prod Folder' = $_.Name 'File Count' = @(Get-ChildItem -LiteralPath $_.FullName -File -Recurse).Count } } $PRODFLDFileCount |Export-Csv -Path C:\Temp\data.csv -NoTypeInformation
COB服务器文件夹及文件计数代码
$COBFLDFileCount = Get-ChildItem -LiteralPath $TRGTLCOBCAS -Directory | ForEach-Object { [pscustomobject] @{ 'COB Folder' = $_.Name 'File Count' = @(Get-ChildItem -LiteralPath $_.FullName -File -Recurse).Count } } $COBFLDFileCount |Export-Csv -Append -Path C:\Temp\data.csv -NoTypeInformation
现有变量输出
$PRODFLDFileCount 输出
Prod Folder File Count ------------ ----------- test 122 dm001 13 dm002 284 dm33 322 dms0011 6
$COBFLDFileCount 输出
COB Folder File Count ------------ ----------- test 11 dm001 13 dm002 2 dm33 32 dms0011 0
解决方案
直接使用Export-Csv -Append会将COB的数据作为新行追加,无法实现列扩展的需求。正确的做法是先将两个数据集按文件夹名称关联,合并为包含所有需要字段的对象后再导出。
修改后的完整代码
# 获取PROD服务器文件夹及文件计数,统一用FolderName字段便于关联 $PRODFLDFileCount = Get-ChildItem -LiteralPath $SRCLPRODCAS -Directory | ForEach-Object { [pscustomobject] @{ 'FolderName' = $_.Name 'ProdFileCount' = @(Get-ChildItem -LiteralPath $_.FullName -File -Recurse).Count } } # 获取COB服务器文件夹及文件计数,统一用FolderName字段便于关联 $COBFLDFileCount = Get-ChildItem -LiteralPath $TRGTLCOBCAS -Directory | ForEach-Object { [pscustomobject] @{ 'FolderName' = $_.Name 'COBFileCount' = @(Get-ChildItem -LiteralPath $_.FullName -File -Recurse).Count } } # 获取所有唯一的文件夹名称,避免遗漏任意一方的文件夹 $allFolderNames = $PRODFLDFileCount.FolderName + $COBFLDFileCount.FolderName | Select-Object -Unique # 合并两个数据集,生成包含并列字段的对象 $combinedData = $allFolderNames | ForEach-Object { $currentFolder = $_ $prodMatch = $PRODFLDFileCount | Where-Object { $_.FolderName -eq $currentFolder } $cobMatch = $COBFLDFileCount | Where-Object { $_.FolderName -eq $currentFolder } [pscustomobject] @{ 'Prod Folder' = $prodMatch.FolderName ?? $currentFolder 'Prod File Count' = $prodMatch.ProdFileCount ?? 0 'COB Folder' = $cobMatch.FolderName ?? $currentFolder 'COB File Count' = $cobMatch.COBFileCount ?? 0 } } # 导出合并后的数据到CSV $combinedData | Export-Csv -Path C:\Temp\data.csv -NoTypeInformation
代码说明
- 统一两个数据集的文件夹名称字段为
FolderName,方便后续关联匹配 - 提取所有唯一的文件夹名称,确保不会遗漏任何一方存在的文件夹
- 对每个文件夹名称,分别匹配PROD和COB的数据,若某一方无对应文件夹则用
0填充计数 - 最终导出的CSV会包含
Prod Folder、Prod File Count、COB Folder、COB File Count四个并列列,满足需求
内容的提问来源于stack exchange,提问作者Puneet Tiwari
相关产品推荐
相关产品推荐

