使用 powershell 在现有 CSV 中添加列 CSV

Add column CSV in existing CSV with powershell

我有一个 Powershell 脚本,它收集备份的大小,并将其导出为 CSV,我想知道是否可以将它添加到下一个 csv 列,或者 excel.

我一直在看文档,因为我认为它在 excel 上看起来更好,但我不能再添加专栏了,我总是从头开始相信它。

$today = (get-date).Date
$backup = Get-VBRBackup | where {$_.info.jobname -eq "A. ProduccionInterna.Infraestructura Backup Copy"}
if ($backup) {
$backup.GetAllStorages() | where {$_.CreationTime.Date -eq $today} | select {$_.PartialPath}, {$_.Stats.BackupSize/1GB} |
export-csv -Path C:\Users\acepero\Documents\test.csv -NoTypeInformation -Delimiter ';'
}

更新

我成功创建了一次新列,然后出现错误:

Select-Object : The property cannot be processed because the property "{$_.PartialPath}, {$_.Stats.BackupSize/1GB} , {$Session.BackupStats.DedupRatio} , 
{$Session.BackupStats.CompressRatio}" already exists.

代码现在具有这种形式

$today = (get-date).Date
$backup = Get-VBRBackup | where {$_.info.jobname -eq "A. ProduccionInterna.Infraestructura Backup Copy"}
if ($backup) {
$backup.GetAllStorages() | where {$_.CreationTime.Date -eq $today} | select {$_.PartialPath}, {$_.Stats.BackupSize/1GB} , {$Session.BackupStats.DedupRatio} , {$Session.BackupStats.CompressRatio} 
(Import-Csv "C:\Users\acepero\Documents\test.csv") |
    Select-Object *, {{$_.PartialPath}, {$_.Stats.BackupSize/1GB} , {$Session.BackupStats.DedupRatio} , {$Session.BackupStats.CompressRatio}} |
Export-csv -Path C:\Users\acepero\Documents\test.csv -NoTypeInformation #-Delimiter ';' 
}

当您从命令获取输出并将其通过管道传输 select 时,您正在创建一个输出对象,该对象具有 selected 值作为属性。这是使用 Get-ChildItem 命令的示例:

$result = Get-ChildItem C:\Temp | select Name, Length

$result 数组包含具有 "Length" 和 "Name" NoteProperties 的对象。当您将该对象通过管道传输到 Export-CSV 时,它会为对象具有的每个 Property/NoteProperty 创建一列。为了'add a column to the CSV',你需要做的就是给对象添加一个NoteProperty。您可以使用 Add-Member cmdlet 执行此操作,如下所示:

$result | Add-Member -MemberType NoteProperty -Name 'ColumnName' -Value 'ColumnValue'

请注意您的操作方式。如果 $result 是单个对象,此命令会将 NoteProperty/Value 对添加到该对象。如果 $result 是一个对象数组,它会将 NoteProperty/Value 对添加到数组中保存的所有对象中。如果需要为每个对象分配不同的值,则需要遍历数组:

ForEach ($res in $result)
{
    $thisvalue = '' #Assign specific value here
    $res | Add-Member -MemberType NoteProperty -Name 'ColumnName' -Value $thisvalue
}

希望对您有所帮助。如果是,请不要忘记采纳答案。