fenster
fenster

Reputation: 1859

Creating custom objects and using the output

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?

Upvotes: 2

Views: 3332

Answers (2)

Shay Levy
Shay Levy

Reputation: 126732

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):

Get-content computers.txt | foreach-object {
    import-csv "$computer.txt" -Header $header | Select -first 1 
} | Export-csv $users -notype

Upvotes: 4

Keith Hill
Keith Hill

Reputation: 201652

Create an array variable and add each $obj to it. After the foreach loop, export the array of objects e.g.:

$arr = @()

foreach (...) {
    ...
    $arr += $obj
}

$arr | Export-csv -path  $users -notype

Upvotes: 2

Related Questions