使用Powershell“where”命令与数组值进行比较

时间:2013-05-07 13:20:33

标签: arrays powershell foreach where

我正试图想办法让这个命令从一个值数组中过滤而不是一个值。目前这是我的代码的方式(并且当$ ExcludeVerA是一个值时它可以工作):

$ExcludeVerA = "7"

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

我希望$ ExcludeVerA有一个像这样的值数组(这当前不起作用):

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

foreach ($x in $ExcludeVerA)
{

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

}

为什么第二段代码不起作用或者我能做什么的其他想法的任何想法?

2 个答案:

答案 0 :(得分:17)

尝试-notcontains

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

所以,如果我理解它,那么

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

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

这是你问题的直接答案。可能的解决方案可能是这样的:

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

它使用正则表达式来完成工作。

答案 1 :(得分:3)

试试这个:

Get-WmiObject -Class Win32_Product -Filter "Name LIKE '%Java%'" | 
Where-Object {$_.Version -notmatch '[734]'}