Thomas Guidry
Thomas Guidry

Reputation: 55

Powershell: How to find an item in an array thats not an exact match?

I have an array of items like so:

$arr = "server1", "server2", server3"

I have a search value:

$ser = "server3-test"

I want to find similar values in the array without doing modifications to the actual value I'm searching for itself (aka string splits etc).

So something like:

if($arr -contains (similar $ser)) {do stuff}

Upvotes: 2

Views: 2007

Answers (1)

briantist
briantist

Reputation: 47792

You can do this by filtering:

if (($arr | Where-Object { $_ -like 'server3*' })) {
    # do stuff
}

if ($arr.Where( { $_ -like 'server3*' } )) {
    # do stuff
}

You can also take advantage of the fact that -like and -match operators can operate on collections, and return a collection that satisfies the condition, and then further on the fact that an empty collection will evaluate $false:

if ($arr -like 'server3*') {
    # do stuff
}

After re-reading your question, I see that this is not quite what you are looking for.

In your example, the value in $arr is a subset of $ser, so you could do this:

if ($arr.Where( { $ser -match $_ } )) { }

But it's not clear if that will always be the case.

Perhaps something more safe, but also more verbose would be to check both against each other:

if (
    $arr | Where-Object {
        $_ -like "*$ser*" -or
        $ser -like "*$_*"
    } ) {
    # do stuff
}

To know what was actually matched, I'd suggest a slightly different approach:

$arr | ForEach-Object {
    if ($_ -like $ser) {
        # do stuff
        # $_ will refer to the array member that was matched
    }
}

The caveat here is that # do stuff will be executed once for every match, instead of once if any match was found.

Another possibility:

$itemsMatched = $arr -like $ser
if ($itemsMatched) {
    # do stuff (executed once)
}

In this case $itemsMatched will contain the array members that matched (it may be more than one).

Upvotes: 1

Related Questions