首页 > 解决方案 > 与 powershell 中的正则表达式数组进行比较

问题描述

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

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

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

标签: arraysregexpowershell

解决方案


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

您只需要遍历列表直到找到匹配项-.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
}

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


推荐阅读