使用 -notcontains 在数组中的字符串中查找子字符串

Using -notcontains to find substring within string within array

我试图避免将嵌套的 ForEach 循环用作较大代码的一部分。为此,我使用了 -notcontains 运算符。基本上,我想查看数组中的字符串中是否存在子字符串。如果存在,什么也不做,如果不存在,打印"Not Found".

这是代码...

$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"
}

我们可以看到 value24 不在数组的任何字符串中。但是,value22 在数组的第二个字符串中。

因此结果应该输出如下...

Not Found

但是,我看到了以下输出...

Not Found
Not Found 2

谁能告诉我为什么会这样?

-contains-notcontains 不针对模式进行操作。

幸运的是,-match-like 以及它们的否定对应物,当与左侧的数组一起使用时,return 满足条件的项目的数组:

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

Returns:

ape
vape

if 语句中,这仍然有效(0 计数结果将被解释为 $false):

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

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

编辑以获得关于我正在寻找的内容的更清晰的答案...

到目前为止,这是我唯一能解决的方法。我希望有一个更清洁的解决方案...

$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"
}

输出将是:

Not Found value24

我的解决方案:

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

使用 V3 .foreach() 方法:

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

还有另一种可能性:

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