跨列将变量写入现有CSV

时间:2018-08-15 20:41:49

标签: powershell export-csv

这是关于Out-File的限制以及将字符串值转换为对象以使用Export-CSV的两部分问题。

我正在研究一个脚本,以提取各种信息并将其添加到现有的csv文档中。我目前正在使用Out-File,但我不认为它具有所需的功能。

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

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

date
computername
username
error

我想读:

date computername username error

我尝试使用Export-CSV,但是由于我的变量是字符串,因此只写字符串长度而不是变量。我很高兴将Export-CSV-Append一起使用,只要它能正确报告项目即可。

如果我们可以使表具有标题,则奖励点:

date computername username error
8/15/2018 A1 Bob PowerIssue
8/15/2018 A2 Tom InternetIssue

1 个答案:

答案 0 :(得分:4)

$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