file - 如何在powershell中比较两个csv文件而不指定属性

标签 file powershell csv comparison

我有两个 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/

相关文章:

java - 从 Android 设备删除内存中的文件?

powershell - PowerShell-如何在一个表中格式化两个不同命令的输出?

powershell - 如果尚未启用 VLAN,请启用 VLAN 并使用 powershell 脚本设置 VLAN ID

powershell - 如何使用powershell将文件中版本列表的三位小数转换为两位小数

php - 使用 PHP 将 CSV 转换为 JSON?

C# 扫描文件夹并打开特定时间后创建的文件

java - 去掉文件路径(home/user/file.txt = file.txt)?

java - 用另一个 ArrayList 中的随机字符串替换 ArrayList 中的特定字符串

Python循环遍历CSV文件及其列

excel - 将 CSV 文件导入 Excel