I'm using the following to read one line from a whole load of text files and then summarize that information into one file.
我正在使用以下内容从一大堆文本文件中读取一行,然后将该信息汇总到一个文件中。
$computers = Get-content computers.txt
$users = users.csv
$header = 'Computer','User','Date','Time'
Foreach ($computer in $computers)
{
$file = $computer +'.txt'
$a = import-csv $file -Header $header | Select -first 1
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Computer ($a.Computer)
$obj | Add-Member NoteProperty User ($a.User)
$obj | Add-Member NoteProperty Date ($a.Date)
$obj | Add-Member NoteProperty Time ($a.Time)
Write-Output $obj
$obj | Export-csv -path $users -notype
}
When I run the code the Write-Output outputs all the records as expected, but the Export-CSV only contains the last record. What am I doing wrong?
当我运行代码时,Write-Output按预期输出所有记录,但Export-CSV仅包含最后一条记录。我究竟做错了什么?
2 个解决方案
#1
You are overwriting the csv file with each loop iteration. I believe the following gives what you're after assuming each csv file has only four columns (i.e Computer,User,Date,Time):
您将在每次循环迭代时覆盖csv文件。我相信以下内容假设您假设每个csv文件只有四列(即计算机,用户,日期,时间):
Get-content computers.txt | foreach-object {
import-csv "$computer.txt" -Header $header | Select -first 1
} | Export-csv $users -notype
#2
Create an array variable and add each $obj to it. After the foreach loop, export the array of objects e.g.:
创建一个数组变量并将每个$ obj添加到它。在foreach循环之后,导出对象数组,例如:
$arr = @()
foreach (...) {
...
$arr += $obj
}
$arr | Export-csv -path $users -notype
#1
You are overwriting the csv file with each loop iteration. I believe the following gives what you're after assuming each csv file has only four columns (i.e Computer,User,Date,Time):
您将在每次循环迭代时覆盖csv文件。我相信以下内容假设您假设每个csv文件只有四列(即计算机,用户,日期,时间):
Get-content computers.txt | foreach-object {
import-csv "$computer.txt" -Header $header | Select -first 1
} | Export-csv $users -notype
#2
Create an array variable and add each $obj to it. After the foreach loop, export the array of objects e.g.:
创建一个数组变量并将每个$ obj添加到它。在foreach循环之后,导出对象数组,例如:
$arr = @()
foreach (...) {
...
$arr += $obj
}
$arr | Export-csv -path $users -notype