how to compare two csv files in powershell without specifying properties

女生的网名这么多〃 提交于 2019-12-19 10:29:58

问题


I have two csv files:

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

The result is as those two files were equal.

It works as expected if I specify the particular property, e.g:

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

How to compare the csv files without specifying the properties. Let's say I would like to compare all properties in the csv file.


回答1:


You can obtain the list of CSV column properties via Get-Member -MemberType NoteProperty, then pass that list to 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:


The answer by latkin will not work. You will get the following exception:

Compare-Object : Cannot convert System.Management.Automation.PSObject to one of the following types {System.String, System.Management.Automation.ScriptBlock}. At line:8 char:19 + Compare-Object <<<< $file1 $file2 -Property $props1 + CategoryInfo : InvalidArgument: (:) [Compare-Object], NotSupportedException + FullyQualifiedErrorId : DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.CompareObjectCommand

It seems that one cannot pass a variable for -Property. It has to be a comma-seperated list of NoteProperties and it cannot be enclosed in single or double quotes.

I've been looking for a way to do this same thing and I still haven't found a way...



来源:https://stackoverflow.com/questions/17934542/how-to-compare-two-csv-files-in-powershell-without-specifying-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!