我正在尝试比较使用Get-ChildItem
cmdlet获得的两个列表。
我了解了Compare-Object
cmdlet,但是在这种情况下,我更喜欢使用foreach,因为它可以访问$file
变量。
$StartingFolderPath = "C:\---\StartingFolder"
$EndingFolderPath = "C:\---\EndingFolder"
$AllStartingFiles = Get-ChildItem $StartingFolderPath
$AllEndingFiles = Get-ChildItem $EndingFolderPath
Write-Host "First folder content:"$AllStartingFiles
Write-Host "Second folder content:" $AllEndingFiles
foreach($file in $AllEndingFiles){
write-Host "Element :" $file.Name
$result = $AllStartingFiles.Contains($file.Name)
write-host $result
if($AllStartingFiles.Contains($file.Name)){
Write-Host "You are here"
Write-Host $file.Name
}
}
但是看来我无法传递if控件if($AllStartingFiles.Contains($file.Name))
,该控件返回false。
输出
First folder content: 1_one.txt 2_two.txt 3_three.txt 5_five.txt
Second folder content: 1_one.txt 2_two.txt 3_three.txt 4_four.txt 5_five.txt
6_six.txt
Element : 1_one.txt
False
Element : 2_two.txt
False
Element : 3_three.txt
False
Element : 4_four.txt
False
Element : 5_five.txt
False
Element : 6_six.txt
False
我也尝试过使用-Contains
运算符,但没有任何运气。
答案 0 :(得分:2)
您在此期间未解决Name
属性
$result = $AllStartingFiles.Contains($file.Name)
正确的方法是:
$result = $AllStartingFiles.Name.Contains($file.Name)
即使只是不想使用Compare-Object
也是如此,因为您担心会丢失文件属性,而事实并非如此。
Compare-Object -ReferenceObject $AllEndingFiles -DifferenceObject $AllStartingFiles -IncludeEqual -ExcludeDifferent | Select-Object -ExpandProperty InputObject
这将为您提供同时出现在列表和属性中的所有文件。
答案 1 :(得分:0)
我不知道不使用比较对象的原因:
> tree /F
├───first
│ 1_one.txt
│ 2_two.txt
│ 3_three.txt
│ 5_five.txt
│
└───second
1_one.txt
2_two.txt
3_three.txt
4_four.txt
5_five.txt
> compare (gci .\first\) (gci .\second\)
InputObject SideIndicator
----------- -------------
4_four.txt =>