使用powershell将查询结果添加到现有csv

使用powershell将查询结果添加到现有csv,powershell,Powershell,我对powershell是新手。我正在尝试将学生考试成绩自动导入我们的学生管理系统。我们收到一个csv文件,其中包含来自多个用户的测试数据。我需要将csv文件中的学生ID转换为系统使用的学生ID。学生可以参加多次考试。示例文件不包含IntID字段,我在试图找到解决方案时添加了该字段 示例CSV文件: ID, Test, Score, Date, IntID 1234, 51, 90, 6/20/2018 1234, 51, 92, 7/15/2018 2345, 67, 95, 7/18/201

我对powershell是新手。我正在尝试将学生考试成绩自动导入我们的学生管理系统。我们收到一个csv文件,其中包含来自多个用户的测试数据。我需要将csv文件中的学生ID转换为系统使用的学生ID。学生可以参加多次考试。示例文件不包含IntID字段,我在试图找到解决方案时添加了该字段

示例CSV文件:

ID, Test, Score, Date, IntID
1234, 51, 90, 6/20/2018
1234, 51, 92, 7/15/2018
2345, 67, 95, 7/18/2018
3456, 77, 84, 7/10/2018
到目前为止,我所拥有的:

add-type -path "D:\app\oracle\client\ODP.NET\bin\2.x\oracle.dataaccess.dll"
$con = new-object oracle.dataaccess.client.oracleconnection("user id=user;password=xxxxx;data source=proddb")
$con.open()

$file = import-csv D:\TestLoad\scores.csv
$file.ID | foreach-object {
$cmd = $con.CreateCommand()
$cmd.CommandText = "select user_id from user where user_ssn = '" + $_ + "' "

$rdr = $cmd.ExecuteReader()
if ($rdr.Read()) {
    $rdr.GetDecimal(0) | select *,@{Name='IntID';Expression={$rdr.GetDecimal(0)}} | export-csv D:\TestLoad\scores.csv -notypeinformation -append -force
}
}
$con.Close()
我的结果:

ID, Test, Score, Date, IntID
1234, 51, 90, 6/20/2018
1234, 51, 92, 7/15/2018
2345, 67, 95, 7/18/2018
3456, 77, 84, 7/10/2018
,,,,"73711"
,,,,"73711"
,,,,"96255"
,,,,"41201"

我觉得我错过了一些简单的东西,但我现在很困惑如何让我的IntID结果正确排列。任何帮助都将不胜感激。

从源文件中删除IntId头,这只会在下面的行没有逗号且内容不匹配时混淆导入Csv

仅在ID上迭代时,当您执行
$file.ID | foreach对象{
时,会丢失所有原始列数据。您稍后尝试使用
select*,…
再次选择它,但尝试馈送
$rdr.GetDecimal(0)| select对象
GetDecimal()的输出
没有原始CSV数据可供选择使用

PowerShell中的CSV处理非常固执己见,您需要的流程是:

导入Csv->管道中的对象->向每个具有IntId名称/值的对象添加新属性->导出为新Csv,或覆盖,但不覆盖
-追加新行

我认为这种方法会奏效:

Add-Type -path "D:\app\oracle\client\ODP.NET\bin\2.x\oracle.dataaccess.dll"

$con = new-object oracle.dataaccess.client.oracleconnection("user id=user;password=xxxxx;data source=proddb")
$con.open()

import-csv D:\TestLoad\scores.csv | foreach-object {

    $cmd = $con.CreateCommand()
    $cmd.CommandText = "select user_id from user where user_ssn = '" + $_.Id + "' "

    $rdr = $cmd.ExecuteReader()

    if ($rdr.Read())
    {

        # $_ being an object representing the current line of the CSV
        $_ | Add-Member -NotePropertyName 'IntId' -NotePropertyValue $rdr.GetDecimal(0) -PassThru
    }
} | Export-Csv D:\TestLoad\scores2.csv -notypeinformation -append -force

$con.Close()

是的,这正是我所需要的。非常感谢你的帮助,特别是告诉我我做错了什么。我感谢你分享你的知识。