【问题标题】:import-csv, add values, export-csv results in file (results in length?)import-csv,添加值,export-csv 结果在文件中(结果长度?)
【发布时间】:2021-02-05 18:08:51
【问题描述】:

我的目标是能够从 csv1 中获取值并将它们更新为 csv2,其中根据 id 的列值找到匹配项。我可以看到输出值正在更新,但是当我尝试将其导出到 csv 文件时,我得到以下内容...

"Length"
"60"
"60"
"60"
"60"

这里是代码。

$inputCsv = Import-CSV './get_values.csv' -delimiter ","
$updateCsv = Import-CSV './set_values.csv' -delimiter ","
$output = $updateCsv | ForEach-Object {
    # Matching value
    $id = $_.id

    # Row of values found in 2nd file matching value from first file
    $rowFound = $inputCsv|Where-object "ID" -EQ $id #

    # Columns to update values
    if($rowFound -ne $Null -and $rowFound -ne ''){
        $_.email = $rowFound.Email
        Write-Output $_.email
        $_.firstname = $rowFound.FirstName
        Write-Output $_.firstname
        $_.lastname = $rowFound.LastName
        Write-Output $_.lastname
    Write-Output "------------------------------------------------------------"
    }
}

$output | Export-Csv 'C:\scripts\powershell\output.csv' -NoTypeInformation

我已经尝试过这里的解决方案:Export-CSV exports length but not name

但我无法让它们中的任何一个工作。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    这是因为您导出的是原始字符串值,而不是结构化对象 - Export-Csv 试图发现输入对象的属性,而字符串只有一个属性 - 长度。

    更改循环体以修改$_,然后在最后输出$_ - 不要尝试在其间输出任何其他内容:

    $output = $updateCsv | ForEach-Object {
        # Matching value
        $id = $_.id
    
        # Row of values found in 2nd file matching value from first file
        $rowFound = $inputCsv | Where-object "ID" -EQ $id #
    
        # Columns to update values
        if($rowFound){
            $_.email = $rowFound.Email
            $_.firstname = $rowFound.FirstName
            $_.lastname = $rowFound.LastName
        }
    
        # output the (perhaps modified) object, nothing else
        $_
    }
    

    【讨论】:

    • 谢谢,也没有在两者之间加上write-output...
    猜你喜欢
    • 2012-06-22
    • 2013-09-07
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 2022-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多