【问题标题】:Powershell - StreamWriter only write first linePowershell - StreamWriter 只写第一行
【发布时间】:2016-08-11 06:48:06
【问题描述】:

我正在编写一个应该导入 csv 的代码 - 更改内容,然后导出到 csv。

我尝试使用 Export-Csv 导出 - 但它只写入字符串的长度 我也尝试使用 StreamWriter - 但它只写入一次 $Resultat

我是 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()

Write-output 以正确的方式显示输出

谁能看到我做错了什么?

【问题讨论】:

    标签: powershell export-to-csv streamwriter


    【解决方案1】:

    试试这个:

    $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"
    

    【讨论】:

    • 感谢您的快速回复。 $Resultat += 正在删除换行符并减慢代码速度。
    • 我想差不多了。现在 csv 包含预期的 17000 行,但单元格中包含 Length
    • 对不起,如果我不清楚这部分。我得到 $result 字符串的长度而不是代码的输出,例如83、82、82、83等
    • 你是我的英雄 :-) 工作就像一个魅力 - 谢谢
    猜你喜欢
    • 2012-02-12
    • 2023-04-05
    • 1970-01-01
    • 2017-08-13
    • 2021-07-10
    • 2015-04-28
    • 2023-03-25
    • 2021-03-20
    • 2011-06-25
    相关资源
    最近更新 更多