【问题标题】:Compare against array of regexes in powershell与 powershell 中的正则表达式数组进行比较
【发布时间】:2021-11-15 23:13:30
【问题描述】:

我正在建立一个白名单比较。它完美地工作,但我想添加包含通配符或正则表达式的字符串的功能,在表示白名单的数组中

反过来比较——在 installed_software 变量中使用通配符很容易,但我不确定如何比较可能是也可能不是正则表达式的字符串数组。我是否需要迭代白名单中的每个元素并进行正则表达式比较?这听起来时间紧迫。

$xxxxx | foreach-object {
    $installed_software = $_
    # Compare the installed application against the whitelist 
    if ( -not $whitelist.Contains( $installed_software ) ) 
    {
        $whitelist_builder += "$installed_software"
    }

【问题讨论】:

标签: arrays regex powershell


【解决方案1】:

我是否需要对白名单中的每个元素进行迭代并进行正则表达式比较?这听起来时间紧迫。

您只需要遍历列表直到找到匹配项 - .Where() 扩展方法对于此类事情是一个不错的选择:

$whitelist = '\bExcel\b','\bWord\b'
$installedSoftware = "Microsoft Office 15.0 Word Application"

if(-not $whitelist.Where({ $installedSoftware -match $_ }, 'First')){
    # no patterns matching the software, add software to builder
}

'First' 模式参数指示 PowerShell 在找到第一个匹配项后立即返回,因此如果 $installedSoftware 的值是 Microsoft Office Excel,它只会进行 1 次 -match 比较

【讨论】:

    【解决方案2】:

    Mathias R. Jessen's helpful answer 的替代方法是使用Select-String 在多个输入字符串中搜索多个模式中的任何一个的能力:

    # The array of whitelist regex patterns.
    $whiteList = '\bExcel\b','\bWord\b'
    
    # The array of strings to filter against the whitelist patterns.
    $arrayOfStrings = 'Foo', 'A Word to the wise', 'Bar', 'Excel we shall'
    
    # Use Select-String to match each input string against
    # all whitelist patterns and return those that do *not* match.
    $notWhiteListed =
      ($arrayOfStrings | Select-String -Pattern $whiteList -NotMatch).Line
    

    $notWhiteListed 则包含以下数组:'Foo', 'Bar'

    注意:

    • 在 PowerShell (Core) 7+ 中,您可以使用 -Raw 开关直接获取(非)匹配字符串,而无需 (...).Line

    【讨论】:

      猜你喜欢
      • 2019-11-29
      • 1970-01-01
      • 2012-01-03
      • 2020-02-29
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多