how to compare two csv files in powershell without specifying properties

后端 未结 2 1920
生来不讨喜
生来不讨喜 2021-01-15 13:29

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

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 14:08

    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
    }
    

提交回复
热议问题