2

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?

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.