0

I'm trying to -match more than one string in a CSV file. Sample CSV below:

Hostname,IpAddress,Domain
x200apple300,1.2.3.4,contoso.local
x200banana300,1.2.3.5,contoso.local
x200orange300,1.2.3.6,contoso.local
x200kiwi300,1.2.3.7,contoso.local

Sample code:

$csv = Import-Csv "C:\Files\csvExample.csv"
$csv | Where-Object {$_.Hostname -match "kiwi"}
# All OK. Now match multiple hostnames.

$csv | Where-Object {$_.Hostname -match "kiwi", "orange"}
# Not working.

$csv | Where-Object {$_.Hostname -contains "apple", "banana"}
# Not working

How can I match multiple hostnames in this example? What am I doing wrong.

2 Answers 2

3

Match takes a regex expression, so you can use an or operator to filter on multiple values.

$csv = Import-Csv "C:\Files\csvExample.csv"
$csv | Where-Object {$_.Hostname -match "kiwi|orange|banana"}
Sign up to request clarification or add additional context in comments.

1 Comment

Or use the -or operator
3

The -match operator expects a regex on the right hand side. I'm not sure what $Value -match $A, $B means; it's not documented that I can see and it seems to always return false from my input.

$_.Hostname -contains "apple", "banana" is backwards. You want either {$_.Hostname -in "apple", "banana"} or {"apple", "banana" -contains $_.Hostname}.

1 Comment

$Value -match $A, $B stringifies the RHS array, so it is effectively the same as $Value -match "$A $B", which is rarely useful; e.g., 'fo o' -match 'o', 'o' is $true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.