Compare a string in one array, with a wildcard string in another Compare a string in one array, with a wildcard string in another powershell powershell

Compare a string in one array, with a wildcard string in another


Have you tried this?

$a = "1","Computer Name","2"$b = "3","4","Full Computer Name Here"foreach ($line in $a ) {    $b -match $line}

EDIT:Probably not the best answer despite it's simplicity as illustrated by @Ansgar in the comments. Sometimes PowerShell is so inconsistent it makes me wonder why I still use it.


Where-Object doesn't work that way. It reads from a pipeline that you don't have in your code. Also, your comparison is backwards, and you must not add wildcard characters to the reference value.

Change your code to something like this:

foreach ($line in $a) {    $b | Where-Object { $_ -like "*${line}*" }}

or like this:

foreach ($line in $a) {    foreach ($line2 in $b) {        if ($line2 -like "*${line}*") { $line2 }    }}

and it will do what you expect.

Edit:

I keep forgetting that comparison operators also work as enumerators, so the latter example could be simplified to something like this (removing the nested loop and conditional):

foreach ($line in $a) {    $b -like "*${line}*"}


$b | Where {$_ | Select-String $a}

Updated 2018-06-23

Credits for LotsPings' comment to minimize it further to:

Apparently, Select-String has already both iterators in itself and therefore it can be simplified to just:

$b | Select-String $a

PS C:\> $a = "1", "Computer Name", "Other Name"PS C:\> $b = "Computer", "4", "Full Computer Name Here", "something else", "Also full computer name here"PS C:\> $b | Select-String $aFull Computer Name HereAlso full computer name here