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

标签 powershell shell 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 ';'
}

更新

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

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 传递时,您正在创建一个输出对象,该对象将选定的值作为属性。以下是使用 Get-ChildItem 命令的示例:

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

$result 数组包含具有“Length”和“Name”NoteProperties 的对象。当您将该对象通过管道传输到 Export-CSV 时,它会为该对象具有的每个 Property/NoteProperty 创建一列。为了“向 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
}

希望这对您有帮助。如果是,请不要忘记接受答案。

关于powershell - 使用 powershell 在现有 CSV 中添加列 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60270797/

相关文章:

以独立于文化的方式进行 Powershell 格式化?!对于数字

powershell - Get-ADGroup 中的格式成员属性

powershell - 使用 SharePoint 2010 的 OData API 替换附加文件

php - 开启PHP xdebug的快捷方式

Linux 备份所有带有时间戳的已知扩展名的文件

bash - 在 bash 脚本中使用空格拆分句子

bash - 回显表情符号时如何在 bash shell 中移动光标?

powershell - 奇怪的PowerShell Exec输出捕获行为

Powershell 压缩文件夹和文件,然后删除旧文件

powershell - 使用 PowerShell Invoke 命令安装软件