1

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"
    }
2
  • Can you show an example of how you'd populate $whitelist? Commented Sep 22, 2021 at 13:17
  • 1
    Adding values to the array is at least as expensive as reading them. Especially if you use the increase assignment operator (+=) to create a collection. Instead, I recommend to use a HashSet. Commented Sep 22, 2021 at 15:25

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.