Cypher236
Cypher236

Reputation: 527

Why isn't -Contains returning true for this?

Here's my code:

while ($looper){
    [array]$destfiles = Get-ChildItem "C:\Users\{redacted}\Documents\test powershell\DEST"
    [array]$srcfiles = Get-ChildItem "C:\Users\{redacted}\Documents\test powershell\SRC" -File -Recurse
    Write-Host $destfiles
    Write-Host $srcfiles
    
    $matchcount = 0
    $matchfiles = ""

    $list = "a.txt","b.txt"

    foreach ($file in $destfiles){
        Write-Host "foreach " $file
        if ($list -contains $file){
            Write-Host "match iteration"
            $matchcount += 1
            # $matchfiles += $file + " "
        }
    }

    if ($matchcount -eq 0){
        Write-Host "break loop"
        break
    }
    else{
        Write-Host "loop"
        Start-Sleep -s 30
    }

    $loopcounter += 1
}

I have identical files in both directories. For the if statement, if I hardcode it (like in the above example) to this:

if ($list -contains $file){

It works as expected. But as soon as I try to actually compare against srcfiles, it doesn't enter the if loop:

if ($srcfiles -contains $file){

What am I doing wrong?

Upvotes: 0

Views: 45

Answers (2)

js2010
js2010

Reputation: 27418

Two objects usually aren't equal unless they're the same object (they're pointers). But comparing string values works. Pay attention to the type of the left operand (the right side gets converted).

$a = get-childitem file
$b = get-childitem file


$a.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     FileInfo                                 System.IO.FileSystemInfo


"$a".gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object


$a -eq $a

True


$a -eq $b

False


"$a" -eq $b

True

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

You're comparing to a [FileInfo] object, not a file name.

Change this if condition:

$list -contains $file

to:

$list -contains $file.Name

Upvotes: 1

Related Questions