2017-09-26 49 views
0

我正在編寫一個函數來比較兩個CSV,但一旦我找到比較部分,就會收到錯誤。 我只想指出那些列入其中之一的元素。用於比較2個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 

那些是用於測試目的看看它是否rks,但現在它甚至沒有開始比較。

當我在控制檯中查找時,兩個CSV會正確加載。

回答

1

我會去這樣的:

我已經添加了名爲「名稱」的第一行上的列名。因此,使用該設置,您可以將其作爲屬性進行訪問。 所以

$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

恐怕比較對象不喜歡的工作。根據我的理解,你正試圖在兩者中找到獨特的物品。最簡單的方法是將兩個CSV添加在一起,然後在要獲取唯一屬性的屬性上執行select-object -Unique

($csv1 + $csv2).Name | Select-Object -Unique 

在這裏,我認爲在CSV數據的列名是「名稱」

+0

我是否能夠指出哪CSV的是commin? – Kevin

+0

這需要更精細的腳本。一種簡單的方法是在每行中添加另一列到您的csv文件[手動或編程]並使用相應的文件名。然後,一旦添加它,每個數據將在新添加的列中有其來源。 如果數據存在於兩個文件中,您將需要額外的邏輯,否則會導致衝突。 –

+0

這聽起來相當困難和困惑壽,所以沒有一個更簡單的方法來得到這個工作? – Kevin