首页 > 解决方案 > 如何比较两个不同 CSV 文件的列?

问题描述

        I am new to powershell, I want to read a csv file with four columns (A,B,C,D), I want to know if column C contains the term "technical" the value of column A remains unchanged, but if column C does not contain the term "technical" I recover its value to put it in column A, and finally I generate a new csv file. Please, can you help me, this is what I did but it doesn't work for the moment.
         This csv file begining:
            
        [![job.csv][1]][1]
 
  $ElementCsv=Import-csv  $env:USERPROFILE\Desktop\Archi\job.csv
    $NewModifiedElement= ForEach($Entry in $ElementCsv){
            $JobstreamColumn=$($Entry_."Jobstream");
            $JobstreamDescription=$($Entry_."Jobstream Description");
            $OpNum= $($Entry_."Op num");
            $Job= $($Entry_."Job");
            $Script=$($Entry_."Script or expected file(s)");
            $Server=$($Entry_."Server");
            $User=$($Entry_."user");
            $Location=$($Entry_."location");
            $JobDescription=$($Entry_."Job Description")
    
            if($Script -ne "technical"){
              
                    $JobstreamColumn=$Script -split"\.";
    
            }else {
                    $JobstreamColumn=$Script;
            }
            $Entry
    }
    $NewModifiedElement | Export-Csv "$env:USERPROFILE\Desktop\Archi\job2.csv" -NoTypeInformation

这是我在运行脚本时收到的错误消息:在 Null 表达式中调用方法是不可能的。在字符 :ChangeColumnValue.ps1:19: 17 $JobstreamColumn=$Script.Split("."); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo : InvalidOperation : (:) [], RuntimeException FullyQualifiedErrorId : InvokeMethodOnNull

    Thank you in advance for your help
    
        
          [1]: https://i.stack.imgur.com/XP7GF.png

为什么我在拆分时会出现此异常?

标签: powershell

解决方案


如果您的 CSV 文件包含列,您可以执行以下操作:

示例 CSV:

    Person1Age,Person1,Person2Age,Person2
    21,Jame,18,Kevin
    24,Dan,14,Chris
    33,April,31,May
    15,Allen,15,Craig

代码:$names = Import-Csv -Path 'C:\names.csv'

    foreach($name in $names)
    {
      $p1 = $($name.Person1);
      $age1 = $($name.Person1Age);
      $p2 = $($name.Person2);
      $age2 = $($name.Person2Age);

       if($age2 -ne '18') {
         
          #Since age2 on the first row equals 18, column1 will retain it's value  
          #of 21, however, since the other rows don't have a value of 18 in age2 
          #column, their values in column1 (age1) will be change to reflect age2.    
          
          $age1 = $age2;
       }
    
      #Results: 21, 14, 31, 15
            
      #Do operations to store the values in another csv file.
    }

推荐阅读