我有两个 csv 文件:
ipaddress,port 10.140.11.1,80 10.140.11.2,80
ipaddress,port 10.140.11.1,80 10.140.11.2,8008
The question is how to compare the files in powershell. I have already tried this:
$file1 = import-csv "csvfile1.csv"
$file2 = import-csv "csvfile2.csv"
Compare-Object $file1 $file2 -IncludeEqual
结果是这两个文件相等。
如果我指定特定属性,它会按预期工作,例如:
Compare-Object $file1 $file2 -IncludeEqual -Property port
如何在不指定属性的情况下比较 csv 文件。假设我想比较 csv 文件中的所有属性。
最佳答案
您可以通过 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
}
关于file - 如何在powershell中比较两个csv文件而不指定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17934542/