Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top