SumoStash
SumoStash

Reputation: 55

powershell filter where object and return exact match

I have $variables and $Array1

$Array1 contains:

FirstName  LastName   ZipCode                          Race

Alice      Jones      {90011, 90017, 90006}            American Indian, Asian, Hispanic 
Allen      Rogers     {90025, 90001}                   African American, American
John       Smith      {90001}                          American
Bob        Wilson     {90025, 90001, 90055, 90084}     African American, American,...
Barbara    Hall       {90025}                          White

I want to loop through $Array1 and check if $Variable is in ZipCode. If it matches then do some stuffs.

What I have is

foreach ($variable in $Variables) {
    $result=$Array1 | Where {$_.ZipCode -match "$variable$"}
} 

For some reason it returns

Allen      Rogers     {90025, 90001}                   African American, American
John       Smith      {90001}                          American 
Bob        Wilson     {90025, 90001, 90055, 90084}     African American, American,...

I want the exact match. Output should be:

John       Smith      {90001}                          American 

I tried regex like

$_.ZipCode -match "^$variable$"

but it didn't work.

Upvotes: 1

Views: 24532

Answers (2)

Rock Lee
Rock Lee

Reputation: 1

You can modify

$_.ZipCode -match "^$variable$" 

to

$_.ZipCode -match ("^"+$variable+"$") 

which will evaluate the regex as you wanted.

Upvotes: 0

Maximilian Burszley
Maximilian Burszley

Reputation: 19654

You need to be using the -ceq for an exact match. This is also a case-sensitive match. -match/-cmatch uses regex to match patterns

A better comparison operator to use, however, would be -contains.

Where-Object { $_.ZipCode -contains "$variable" }

Make sure both comparisons match type. If your array uses [Int], make sure you're comparing to an [Int] object. This can further be simplified in PSv3+:

? ZipCode -contains $variable

Edit for OP:

| Where-Object { ($_.ZipCode.Count -eq 1) -and ($_.ZipCode -eq $variable) }

Upvotes: 2

Related Questions