我正在编写一个比较两个CSV的函数,但是一旦到达比较部分,我就会收到错误。 我只想指出那些列在其中一个中的元素。
实际代码
function Compare ($location1, $location2)
{
#work in progress
$CSV1 = Import-Csv -Path $location1 -UseCulture
$CSV2 = Import-Csv -Path $location2 -UseCulture
$Compared = Compare-Object -ReferenceObject $CSV1 -DifferenceObject $CSV2 |
select -ExpandProperty InputObject |
sort
[void] $CSV1
[void] $CSV2
return $Compared
}
以及来自两个CSV的代码段:
代码段A:
a b c d e f g
摘录B:
a b c d e h f g h i j
这些是用于测试目的,看它是否有效,但现在它甚至没有开始比较。
当我在控制台中查找时,两个CSV正确加载。
答案 0 :(得分:1)
我会这样做:
我在名为“Name”的第一行添加了一个列名。因此,使用该集,您可以将其作为属性访问。 所以
$CSV1 = $null
$CSV2 = $null
$CSV1 = Import-Csv -Path 'C:\temp\pos\reference.csv'
$CSV2 = Import-Csv -Path 'C:\temp\pos\difference.csv'
$dif = Compare-Object -ReferenceObject $CSV1 -DifferenceObject $CSV2 -Property Name
foreach($y in $dif){
if($y.SideIndicator -eq "=>"){
write-output $y.name "Is present in the difference but not in reference."
}
if($y.SideIndicator -eq "<="){
write-output $y.Name "Is present in reference but not in difference"
}
}
<# content csv1 (reference.csv)
Name
a
b
c
5
d
e
f
g
9
#>
<#content csv2 (difference.csv)
Name
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
#>
这会给我输出:
h Is present in the difference but not in reference.
i Is present in the difference but not in reference.
j Is present in the difference but not in reference.
k Is present in the difference but not in reference.
l Is present in the difference but not in reference.
m Is present in the difference but not in reference.
n Is present in the difference but not in reference.
o Is present in the difference but not in reference.
p Is present in the difference but not in reference.
5 Is present in reference but not in difference
9 Is present in reference but not in difference
答案 1 :(得分:1)
我担心比较对象不能像那样工作。根据我的理解,您正在尝试在两者中找到独特的项目。最简单的方法是将两个CSV一起添加,并在要获得唯一属性的属性上执行select-object -Unique
。
($csv1 + $csv2).Name | Select-Object -Unique
我假设CSV中数据的列名是&#39;名称&#39;