File1
"FACILITY","FILENAME"
"16","abc.txt"
"16","def.txt"
"12","abc.txt"
"17","def.txt"
"18","abc.txt"
"19","abc.txt"
File2
"FACILITY","FILENAME"
"16","jkl.txt"
"16","abc.txt"
"12","abc.txt"
"17","jkl.txt"
"18","jkl.txt"
"19","jkl.txt"
我正在寻找以下输出:
"FACILITY","FILENAME"
"16","abc.txt"
"12","abc.txt"
对于File2中的每个FILENAME,我想按每个功能列出文件名是否在File1中。因此,如果在File1的FACILITY 20旁边列出了文件qwerty.txt,并且它与File2中的FILENAME与文件名qwerty.txt匹配在同一行,则吐出输出。
假设有一个用于不同设施的qwerty.txt文件,我不希望在输出中显示该文件。
这是我尝试过的方法,但是我觉得我对这些命令很了解,因为我不完全理解它们。
$file1 = Import-Csv $scriptPath'\loadedfiles.txt' -Delimiter ','
$file2 = Import-Csv $scriptPath'\filenames.txt' -Delimiter ','
$Header = $file1 | Get-Member | Where-Object -FilterScript {$_.MemberType -eq 'FACILITY'} | Select-Object -ExpandProperty FILENAME
Compare-Object -ReferenceObject $file1 -DifferenceObject $file2 -Property 'FILENAME' -PassThru | Select-Object -Property $Header |
Export-Csv -Path $scriptPath\test.csv -NoTypeInformation
我已经看到了很多有关如何对两个列表进行比较的示例,但是我需要将一个属性与另一个属性进行比较,这就是为什么我一直在努力寻找Google答案的原因。
答案 0 :(得分:5)
Property参数接受一个数组,因此只需指定两个属性:
Compare-Object $file1 $file2 -Property 'Facility','Filename' -IncludeEqual -ExcludeDifferent -PassThru|select * -Exclude SideIndicator|export-csv -notype $scriptpath\test.csv
这就是我测试的方式,我从重新创建源数据开始(我没有制作文件,只是复制了文本并使用了convertfrom-csv
,但实际上应该是相同的):
PS C:\Users\TMTech> $file1='"FACILITY","FILENAME"
"16","abc.txt"
"16","def.txt"
"12","abc.txt"
"17","def.txt"
"18","abc.txt"
"19","abc.txt"'|convertfrom-csv
PS C:\Users\TMTech> $file2='"FACILITY","FILENAME"
"16","jkl.txt"
"16","abc.txt"
"12","abc.txt"
"17","jkl.txt"
"18","jkl.txt"
"19","jkl.txt"'|convertfrom-csv
然后我将Compare-Object
与一些基本参数一起使用:
PS C:\Users\TMTech> Compare-Object $file1 $file2 -Property 'Facility','Filename'
Facility Filename SideIndicator
-------- -------- -------------
16 jkl.txt =>
17 jkl.txt =>
18 jkl.txt =>
19 jkl.txt =>
16 def.txt <=
17 def.txt <=
18 abc.txt <=
19 abc.txt <=
由此,我排除了差异,并包括了相同之处,然后将其发送到Select-Object
,以删除由SideIndicator
添加的Compare-Object
属性:
PS C:\Users\TMTech> Compare-Object $file1 $file2 -Property 'Facility','Filename' -IncludeEqual -ExcludeDifferent -PassThru|select * -exclude sideindicator
FACILITY FILENAME
-------- --------
16 abc.txt
12 abc.txt
看到您想要的输出后,我建议将管道输送到Export-Csv
以将其输出到文件中。这一切对我来说都很好,所以如果对您不起作用,请检查您的源文件并确保列标题相同,或者文件中的数据格式是否稍有不同(例如完整路径与文件名或东西)。