Search code examples
powershellexport-to-csvstreamwriter

Powershell - StreamWriter only write first line


I´m working on a code that is supposed to import-csv - change the content, and then export to csv.

I´ve tried to export with Export-Csv - but it only writes the lenght of the string I also tried with StreamWriter - but it only writes $Resultat once

I am new to PowerShell :-)

$workfile = import-csv "X:\powershell\converter\test.csv" -Delimiter ';'

ForEach ($item in $workfile)
{
$Id = $item.("ID")
$Maaler = $item.("Maaler")
$Fra = $item.("Fra")
$Til = $item.("Til") 

#Dato gymnastik
$Tilto = $item.("Til")
$Tilto = $Tilto.substring(0,10)


$Til = $Til.substring($Til.length - 8, 8)
$Forbrug = $item.("Forbrug")
$Enhed = $item.("Enhed")
$aflaesningstype = $item.("Aflæsningstype?")
$T = ".000+02:00"

$Resultat = $Tilto + "T" + $Til + $T + ',"' + $Maaler + '","' + '","' + '","' + '","' + '","' + $Forbrug + '","' + $Enhed + '","' + '255"'

Write-output "$Resultat"
}
$Resultat | Export-Csv "X:\powershell\behandlet\Output $(get-date -f dd-MM-yyyy-hh-mm-ss).csv" -Delimiter ',' -NoType

#$fhStream = [System.IO.StreamWriter] "X:\powershell\behandlet\Output $(get-date -f dd-MM-yyyy-HH-mm-ss).csv" 
#$fhStream.WriteLine($Resultat)
#$fhStream.Close()

The Write-output shows the output in the right way

Can anyone see what I am doing wrong ?


Solution

  • Try this:

    $workfile = import-csv "X:\powershell\converter\test.csv" -Delimiter ';'
    $result = New-Object System.Collections.ArrayList
    ForEach ($item in $workfile)
    {
    $Id = $item.("ID")
    $Maaler = $item.("Maaler")
    $Fra = $item.("Fra")
    $Til = $item.("Til") 
    
    #Dato gymnastik
    $Tilto = $item.("Til")
    $Tilto = $Tilto.substring(0,10)
    
    
    $Til = $Til.substring($Til.length - 8, 8)
    $Forbrug = $item.("Forbrug")
    $Enhed = $item.("Enhed")
    $aflaesningstype = $item.("Aflæsningstype?")
    $T = ".000+02:00"
    
    $result += $Tilto + "T" + $Til + $T + ',"' + $Maaler + '","' + '","' + '","' + '","' + '","' + $Forbrug + '","' + $Enhed + '","' + '255"'
    }
    $result | Out-File "X:\powershell\behandlet\Output $(get-date -f dd-MM-yyyy-hh-mm-ss).csv"