How to map 2 arrays of object using PowerShell?

Viewed 513

I would like to map an array object. I need to find the matched object of array. After the object match, I need to stop checking other objects, then continue to the next process.

I tried this, but it always return not match, even if the array object match exists.

$ID = @("8537", "8538", "8539", "8540", "85AC", "85DE", "82EA")
$Signal = @("8537", "8220")


for ($i = 0; $i -lt $Signal.count; $i++)
{
     if ($Signal[$i] -like "$ID[$i]")
     {
          "found ‘$($Signal[$i])’
          at index $i"
          
          # Do some process
     }
     else {
          
          "Not Match"

          # Do some process
     }

}
3 Answers

Something like that you should test :

cls
$ID = @("8538", "8539", "8540", "85AC", "85DE", "82EA","8537")
$Signal = @("8537","8220","85DE")

for ($i = 0; $i -lt $ID.count; $i++) {
    for ($j = 0; $j -lt $Signal.count; $j++) {

        if ($ID[$i] -like $Signal[$j])
        {
            "found $($ID[$i]) at index $i"  
            # Do some process
        } 
        else 
        {  
          "Not Match"
          # Do some process
        }
    }
}

As mentioned in my comment above - to make your example work you can use a nested loop like this:

$ID = @("8537", "8538", "8539", "8540", "85AC", "85DE", "82EA")
$Signal = @("8234", "8512", "8220")
$MatchFound = $false

for ($i = 0; $i -lt $Signal.count; $i++) {
    for ($x = 0; $x -lt $ID.Count; $x++) {
        if ($Signal[$i] -eq $ID[$x]) {
            "found '$($Signal[$i])' at index $i"
            $MatchFound = $true
        }
    }
}

if (-not $MatchFound) {
    "No match was found"
}

If you have a complex object you want to compare you can take a look at the cmdlet Compare-Object.

If you need to go Match process if exists at least 1 match object, you can try this:

$ID = @("8538", "8539", "8540", "85AC", "85DE", "82EA","8537")
$Signal = @("8537","8220","85DE")

$matched = $false

for ($i = 0; $i -lt $ID.count; $i++) {
    if ($matched) {
        break
    }

    for ($j = 0; $j -lt $Signal.count; $j++) {

        if ($ID[$i] -like $Signal[$j])
        {
            $matched = $true
            "found $($ID[$i]) at index $i"
            break
        } 
    }
}

if ($matched) {
    # Do some process
} else {
    "Not Match"
    # Do some process
}
Related