代码之家  ›  专栏  ›  技术社区  ›  Garrett

将变量写入跨列的现有CSV

  •  1
  • Garrett  · 技术社区  · 7 年前

    Out-File 将字符串值转换为要使用的对象 Export-CSV

    我正在编写一个脚本来提取各种信息并将其添加到现有的CSV文档中。我正在使用 输出文件

    $date, $computerName, $env:UserName, 'error' | Out-File $report -Append
    

    上面将所有数据添加到一个列中,例如:

    date
    computername
    username
    error
    

    我想读一下:

    date computername username error
    

    导出CSV ,但由于我的变量是字符串,所以它只写字符串长度而不是变量。我很乐意使用 具有 -Append 只要它报告的项目正确。

    如果我们能让表格的标题如下:

    date computername username error
    8/15/2018 A1 Bob PowerIssue
    8/15/2018 A2 Tom InternetIssue
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   BenH    7 年前

    $date, $computerName, $env:UserName, 'error' 是一个正在转换为字符串数组的集合。那么 Out-File 取数组中的每个元素,每行吐出一个元素。

    你可以生成一个字符串。例如,

    "$date, $computerName, $env:UserName, error" | Out-File $report -Append
    

    但更好的方法是创建一个对象,然后将其导出到csv。下面是一个使用 [pscustomobject] 需要PS3+

    $ExampleObjects = @(
        [pscustomobject]@{
            Date         = Get-Date
            ComputerName = 'A1'
            UserName     = 'Bob'
            Error        = 'PowerIssue'
        },
        [pscustomobject]@{
            Date         = Get-Date
            ComputerName = 'A2'
            UserName     = 'Tom'
            Error        = 'InternetIssue'
        }
    )
    
    $ExampleObjects | Export-CSV $report -Append -NoTypeInformation
    
    推荐文章