【问题标题】:how to compare two csv files in powershell without specifying properties如何在不指定属性的情况下在powershell中比较两个csv文件
【发布时间】:2013-07-29 20:42:52
【问题描述】:

我有两个 csv 文件:

IP地址,端口 10.140.11.1,80 10.140.11.2,80 IP地址,端口 10.140.11.1,80 10.140.11.2,8008

问题是如何比较 powershell 中的文件。我已经尝试过了:

$file1 = import-csv "csvfile1.csv"
$file2 = import-csv "csvfile2.csv"
Compare-Object $file1 $file2 -IncludeEqual

结果是这两个文件相等。

如果我指定特定属性,它会按预期工作,例如:

Compare-Object $file1 $file2 -IncludeEqual -Property port

如何在不指定属性的情况下比较 csv 文件。假设我想比较 csv 文件中的所有属性。

【问题讨论】:

    标签: file powershell csv comparison


    【解决方案1】:

    您可以通过Get-Member -MemberType NoteProperty 获取CSV 列属性列表,然后将该列表传递给Compare-Object

    # get list of CSV properties
    $props1 = $file1 | gm -MemberType NoteProperty | select -expand Name | sort | % {"$_"}
    $props2 = $file2 | gm -MemberType NoteProperty | select -expand Name | sort | % {"$_"}
    
    # first check that properties match (can omit this step if you know for sure they will be)
    if(Compare-Object $props1 $props2)
    {
        throw "Properties are not the same! [$props1] [$props2]"
    }
    # pass properties list to Compare-Object
    else
    {
        Compare-Object $file1 $file2 -Property $props1
    }
    

    【讨论】:

      【解决方案2】:

      latkin 的回答是行不通的。 你会得到以下异常:

      Compare-Object:无法将 System.Management.Automation.PSObject 转换为以下类型之一 {System.String, System.Management.Automation.ScriptBlock}。 在行:8 字符:19 + 比较对象

      似乎无法为 -Property 传递变量。它必须是一个以逗号分隔的 NoteProperties 列表,并且不能用单引号或双引号括起来。

      我一直在寻找一种方法来做同样的事情,但我仍然没有找到方法......

      【讨论】:

      • 看来此错误发生在 PowerShell 版本 2 中,但不在 PowerShell 版本 3 中
      • 我编辑了 latkin 的答案来解决这个问题。该| % {"$_"} 会将列表转换为字符串列表,而不是 PSObject。这就是问题所在。
      猜你喜欢
      • 2017-08-25
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多