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

Alb*_*rés 2 shell powershell powershell-3.0 veeam

我有一个 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 ';'
}
Run Code Online (Sandbox Code Playgroud)

更新

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

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

代码现在具有这种形式

$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 ';' 
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*hew 5

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

$result = Get-ChildItem C:\Temp | select Name, Length
Run Code Online (Sandbox Code Playgroud)

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

$result | Add-Member -MemberType NoteProperty -Name 'ColumnName' -Value 'ColumnValue'
Run Code Online (Sandbox Code Playgroud)

小心你如何做这件事。如果 $result 是单个对象,则此命令会将 NoteProperty/Value 对添加到该对象。如果 $result 是一个对象数组,它将将该 NoteProperty/Value 对添加到数组中保存的所有对象中。如果需要为每个对象分配不同的值,则需要迭代数组:

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

我希望这可以帮助你。如果是的话,请不要忘记接受答案。