简体   繁体   中英

Powershell comparing two List with foreach

I'm trying to compare two lists that I obtained with the Get-ChildItem cmdlet.

I read about the Compare-Object cmdlet, but in this context I would prefer doing with a foreach because is useful to have access to the $file variable.

$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
    }    
}

But it seems that I cannot pass the if control, if($AllStartingFiles.Contains($file.Name)) which returns false.

OUTPUT

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

I've also tried with the -Contains operator, but without any luck.

You didn't address the Name attribute during

$result = $AllStartingFiles.Contains($file.Name)

The correct way would be:

$result = $AllStartingFiles.Name.Contains($file.Name)

Never the less if only don't want to use Compare-Object because you are scared you'll lose the file attributes, this is not the case.

Compare-Object -ReferenceObject $AllEndingFiles -DifferenceObject $AllStartingFiles -IncludeEqual -ExcludeDifferent | Select-Object -ExpandProperty InputObject

This will give you all the files that appear in both lists and their attributes.

I don't know of a reason not to use compare-object:

> 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  =>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM