Home > OS >  Compare against array of regexes in powershell
Compare against array of regexes in powershell

Time:09-23

I'm working on building a whitelist comparison. It works perfectly, but I'd like to add the ability to have strings containing wildcards or regex included in the array representing the whitelist.

Comparing the other way around - with wildcards in the installed_software variable is easy enough, but I'm not sure how to tackle comparing an array of strings that may or may not be regular expressions. Do I need to iterate against each element in the whitelist and do a regex comparison? That sounds time intense.

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

CodePudding user response:

Do I need to iterate against each element in the whitelist and do a regex comparison? That sounds time intense.

You only need to iterate through the list until you find a match - the .Where() extension method is a good option for this kind of thing:

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

The 'First' mode argument instructs PowerShell that it can return as soon as it finds the first match, so if the $installedSoftware value had been Microsoft Office Excel, it would have only done 1 -match comparison

CodePudding user response:

An alternative to Mathias R. Jessen's helpful answer is to use Select-String's ability to search for any of multiple patterns in multiple input strings:

# 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 then contains the following array: 'Foo', 'Bar'.

Note:

  • In PowerShell (Core) 7 you could use the -Raw switch to get the (non-)matching strings directly, without the need for (...).Line.
  • Related