Powershell - 比较两个csv行并在第三个中写入结果

时间:2014-10-15 14:28:57

标签: powershell csv compare

我有两个csv列,我需要比较这两列并将结果写在第三列(结果)。

  

“线”, “路径”, “结果”

     

“RETENTION_LEVEL 3 1 1 1 1 1 1 1 1 1”,“C:\ Veritas \ NetBackup \ db \ class \ policy-v- \ schedule \ cum \ info”,

如何使第三列的变量可设置?

#Write retention and policy in a csv file. 
$file="C:\Users\toto\schedules.csv"
#Write analysis results in a final csv.
$finalFile="C:\Users\toto\bad_retention.csv"
#query to find information based on the retention level and policy + export in the csv
$find=Get-ChildItem "C:\Veritas\NetBackup\db\class\" -recurse | Select-String -pattern "RETENTION_LEVEL" | Select line,path,@{Expression={$_.result};Label="Result";} | Export-CSV $file –NoTypeInformation

        (Import-Csv $file -Delimiter ',')

        ForEach-Object{
            if(($_.line -match "RETENTION_LEVEL 1 1 1 1 1 1 1 1 1 1") -and ($_.path -match "-v-"))
            {
             $_.result="BAD RETENTION"
             echo $_result;
            }
            else
            {
             $_.result="OK";
             echo $_result;
            }
        } | Export-CSV $finalFile –NoTypeInformation
Property 'result' cannot be found on this object; make sure it exists and is settable.
At C:\Users\toto\Documents\bad_retention.ps1:28 char:17
+              $_. <<<< result="OK";
    + CategoryInfo          : InvalidOperation: (result:String) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound

2 个答案:

答案 0 :(得分:0)

未经测试:

Get-ChildItem "C:\Veritas\NetBackup\db\class\" -recurse |
 Select-String -pattern "RETENTION_LEVEL" |
 Select line,path,@{
  Label = 'result'
  Expression = {('OK','BAD RETENTION')[($_.line -match "RETENTION_LEVEL 1 1 1 1 1 1 1 1 1 1") -and ($_.path -match "-v-")]}
  } |
  Export-CSV $file –NoTypeInformation

答案 1 :(得分:0)

使用下面的语法,它可以“:

Expression = {('OK','BAD RETENTION')[($_.line -eq "RETENTION_LEVEL 1 1 1 1 1 1 1 1 1 1")]}