Using Powershell "where" command to compare against Array of values

57,999

Solution 1

Try -notcontains

where ({ $ExcludeVerA -notcontains $_.Version })

so if I understand it corretly, then

$ExcludeVerA = "7", "3", "4"

$java = Get-WmiObject -Class win32_product | where { $_.Name -like "*Java*"} |
where ({ $ExcludeVerA -notcontains $_.Version })

That was direct answer to your question. Possible solution might be something like this:

$ExcludeVerA = "^(7|3|4)\."
$java = Get-WmiObject -Class win32_product | 
          where { $_.Name -like "*Java*"} |
          where { $_.Version -notmatch $ExcludeVerA}

it uses regex to get job done.

Solution 2

Try this:

Get-WmiObject -Class Win32_Product -Filter "Name LIKE '%Java%'" | 
Where-Object {$_.Version -notmatch '[734]'}
Share:
57,999
ThreePhase
Author by

ThreePhase

Updated on August 30, 2020

Comments

  • ThreePhase
    ThreePhase over 3 years

    I'm trying to figure out a way to get this command to filter from an array of values as opposed to one value. Currently this is how my code is (and it works when $ExcludeVerA is one value):

    $ExcludeVerA = "7"
    
    $java = Get-WmiObject -Class win32_product | where { $_.Name -like "*Java*"} |
    where ({ $_.Version -notlike "$ExcludeVerA*" })
    

    And I'd like $ExcludeVerA to have an array of values like so (this currently doesn't work):

    $ExcludeVerA = "7", "3", "4"
    
    foreach ($x in $ExcludeVerA)
    {
    
    $java = Get-WmiObject -Class win32_product | where { $_.Name -like "*Java*"} |
    where ({ $_.Version -notlike "$ExcludeVerA*" })
    
    }
    

    Any ideas of why this second block of code doesn't work or other ideas of what I can do?

  • ThreePhase
    ThreePhase almost 11 years
    The first way doesn't work because the $_.version properties of these objects is typically a long number like: 7.01.04756 and I need to filter by only the first number (i.e. I need to search 7*).
  • ThreePhase
    ThreePhase almost 11 years
    However, the second way you posted using regular expressions works beautifully! And it's simple and elegant. It's also introduced me to regular expressions, so thanks for that :)
  • ThreePhase
    ThreePhase almost 11 years
    Thing is, I need it to notmatch 7*, not just 7, as the version numbers tend to be long (but the stuff after the 7 doesn't matter. Using regular expressions as suggested in Stej's answer did the trick. Thanks, though.