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

标签 powershell powershell-3.0

我试图避免将嵌套的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/

相关文章:

xml - powershell XML Writer 嵌套循环

powershell - 从 WinRT 应用调用 PowerShell

powershell - 当文件没有标题行时,如何使用 Import-CSV 导入制表符分隔的文本文件?

c# - 调试 PowerShell 脚本

xml - Select-Xml 仅显示第一个节点中的子节点

PowerShell 函数参数语法

xml - 如何使用 Powershell 将 XML 正确导出到文件

powershell - 我可以为 PowerShell 中的参数指定条件默认值吗?

Powershell:设置计划任务在用户未登录时运行

windows - 无法获取服务 Powershell 的状态