2

我有两个 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 文件中的所有属性。

4

2 回答 2

4

您可以通过 获取 CSV 列属性列表Get-Member -MemberType NoteProperty,然后将该列表传递给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
}
于 2013-07-29T21:42:40.140 回答
0

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

比较对象:无法将 System.Management.Automation.PSObject 转换为以下类型之一 {System.String, System.Management.Automation.ScriptBlock}。在 line:8 char:19 + Compare-Object <<<< $file1 $file2 -Property $props1 + CategoryInfo : InvalidArgument: (:) [Compare-Object], NotSupportedException + FullyQualifiedErrorId : DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.CompareObjectCommand

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

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

于 2014-04-02T23:45:52.030 回答