我试图避免将嵌套的ForEach循环用作较大代码的一部分。为此,我正在使用-notcontains运算符。基本上,我想查看数组中的字符串中是否存在子字符串。如果存在,则不执行任何操作,如果不存在,则打印“未找到”。
这是代码...
$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
谁能告诉我为什么会这样吗?
最佳答案
我的解决方案:
($arr | foreach {$_.contains('"value24"')}) -contains $true
使用V3 .foreach()方法:
($arr.ForEach({$_.contains('"value24"')}).contains($true))
还有另一种可能性:
[bool]($arr.where({$_.contains('"value24"')}))
关于powershell - 使用-notcontains在数组内的字符串中查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35801685/