Fiddle Freak
Fiddle Freak

Reputation: 2041

Using -notcontains to find substring within string within array

I'm trying to avoid using nested ForEach Loop as part of a larger code. To do this, I'm using the -notcontains operator. Basically, I want to see if a substring exists within a string within an array. If it exists, do nothing, if it does not exist, print "Not Found".

Here is the code...

$arr = @('"value11","value21","value31"','"value12","value22","value32"','"value13","value23","value33"')

if ($arr -notcontains "*`"value24`"*")
{
    Write-Host "Not Found"
}

if ($arr -notcontains "*`"value22`"*")
{
    Write-Host "Not Found 2"
}

We can see that value24 is not within any strings of the array. However, value22 is within the 2nd string in the array.

Therefor the results should output the following...

Not Found

However, instead I see the following output...

Not Found
Not Found 2

Can anyone tell me why this is happening?

Upvotes: 1

Views: 2145

Answers (3)

mjolinor
mjolinor

Reputation: 68263

My take on a solution:

($arr | foreach {$_.contains('"value24"')}) -contains $true

Using the V3 .foreach() method:

($arr.ForEach({$_.contains('"value24"')}).contains($true))

And yet another possibility:

[bool]($arr.where({$_.contains('"value24"')}))

Upvotes: 2

Fiddle Freak
Fiddle Freak

Reputation: 2041

Edit for clearer answer on what I'm looking for...

This is the only way I'm able to figure this out so far. I hope there is a much cleaner solution...

$arr = @('"value11","value21","value31"','"value12","value22","value32"','"value13","value23","value33"')

$itemNotFound = $true
ForEach ($item in $arr)
{
    If ($itemNotFound)
    {
        If ($item -like "*`"value24`"*")
        {
            $itemNotFound = $false
        }
    }

}
if ($itemNotFound)
{
    Write-Host "Not Found value24"
}


$itemNotFound = $true
ForEach ($item in $arr)
{
    If ($itemNotFound)
    {
        If ($item -like "*`"value22`"*")
        {
            $itemNotFound = $false
        }
    }

}
if ($itemNotFound)
{
    Write-Host "Not Found value22"
}

output will be:

Not Found value24

Upvotes: 0

briantist
briantist

Reputation: 47792

-contains and -notcontains don't operate against patterns.

Luckily, -match and -like and their negative counterparts, when used with an array on the left side, return an array of the items that satisfy the condition:

'apple','ape','vape' -like '*ape'

Returns:

ape
vape

In an if statement, this still works (a 0 count result will be interpreted as $false):

$arr = @('"value11","value21","value31"','"value12","value22","value32"','"value13","value23","value33"')

if ($arr -notlike "*`"value24`"*")
{
    Write-Host "Not Found"
}

Upvotes: 3

Related Questions