You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell关联两个CSV文件 创建类匹配数据生成新CSV

PowerShell 双CSV关联匹配导出解决方案

现有代码问题说明

  • 你定义的$FinalEmployeeReport哈希表键规则混乱,先后使用last_name、employee_id作为键,会出现键重复报错,也无法存储完整的实例信息
  • 关联匹配的循环逻辑错误:遍历支付对象时嵌套遍历$Payment本身,无法获取员工实例完成匹配
  • 没有构造符合导出要求的合并字段对象,无法直接生成CSV

修正后完整代码

# 员工类定义(原逻辑保留)
class Employee {
    [Int]$id
    [String]$first_name
    [String]$last_name
    [String]$email
    [String]$city
    [String]$ip_address
    Employee ([Int]$id,[String]$first_name,[String]$last_name,[String]$email,[String]$city,[String]$ip_address){
        $This.id = $id
        $This.first_name = $first_name
        $This.last_name = $last_name
        $This.email = $email
        $This.city = $city
        $This.ip_address = $ip_address
    }
}
# 支付类定义(原逻辑保留)
class Payment{
    [Int]$id
    [Int]$employee_id
    [String]$payment
    [String]$code
    Payment ([Int]$id,[Int]$employee_id,[String]$payment,[String]$code){
        $This.id = $id 
        $This.employee_id = $employee_id
        $This.payment = $payment
        $This.code = $code
    }
}
# 导入CSV文件
$ImportedEmployees = Import-Csv ".\Employee.csv" 
$ImportedPayments = Import-Csv ".\Payments.csv" # 注意文件名和实际存储一致
# 构建员工ID为键的哈希表,用于快速匹配
$employeeMap = @{}
foreach ($emp in $ImportedEmployees) {
    $employeeObj = [Employee]::new([int]$emp.id, $emp.first_name, $emp.last_name, $emp.email, $emp.city, $emp.ip_address)
    $employeeMap[$employeeObj.id] = $employeeObj
}
# 遍历所有支付记录,关联匹配员工,生成合并对象
$mergedResult = foreach ($pay in $ImportedPayments) {
    $paymentObj = [Payment]::new([int]$pay.id, [int]$pay.employee_id, $pay.payment, $pay.code)
    # 匹配对应员工
    if ($employeeMap.ContainsKey($paymentObj.employee_id)) {
        $matchedEmp = $employeeMap[$paymentObj.employee_id]
        # 构造合并后的导出对象,字段可按需增减
        [PSCustomObject]@{
            employee_id = $matchedEmp.id
            first_name = $matchedEmp.first_name
            last_name = $matchedEmp.last_name
            email = $matchedEmp.email
            city = $matchedEmp.city
            ip_address = $matchedEmp.ip_address
            payment_id = $paymentObj.id
            payment_amount = $paymentObj.payment
            payment_code = $paymentObj.code
        }
    }
}
# 导出合并后的CSV文件
$mergedResult | Export-Csv -Path ".\MergedEmployeePayment.csv" -NoTypeInformation -Encoding UTF8

关键逻辑说明

  • 用员工ID作为键构建哈希表,匹配效率远高于嵌套循环,不会出现重复遍历的性能问题
  • 合并对象的字段可根据作业要求调整,增删对应属性即可
  • Export-Csv的-NoTypeInformation参数会去掉PowerShell默认生成的类型标识行,输出标准CSV格式;指定-Encoding UTF8可避免中文乱码
  • 如果需要保留没有对应支付记录的员工,可额外遍历$employeeMap的所有值,补充到$mergedResult中即可

内容的提问来源于stack exchange,提问作者Elijah Robinson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:36:01