【问题标题】:Using Powershell "where" command to compare against Array of values使用 Powershell“where”命令与值数组进行比较
【发布时间】:2013-05-01 11:20:24
【问题描述】:

我试图找出一种方法来让这个命令从一组值而不是一个值中过滤。目前我的代码是这样的(当 $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*" })

}

关于为什么第二个代码块不起作用的任何想法或关于我可以做什么的其他想法?

【问题讨论】:

    标签: arrays powershell foreach where


    【解决方案1】:

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

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

    【讨论】:

    • 第一种方法不起作用,因为这些对象的 $_.version 属性通常是一个长数字,例如:7.01.04756,我只需要按第一个数字过滤(即我需要搜索 7*)。
    • 但是,您使用正则表达式发布的第二种方式效果很好!它简单而优雅。它还向我介绍了正则表达式,非常感谢 :)
    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 问题是,我需要它不匹配 7*,而不仅仅是 7,因为版本号往往很长(但 7 之后的东西并不重要。使用 Stej 中建议的正则表达式答案成功了。不过,谢谢。
    猜你喜欢
    • 2019-04-06
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    相关资源
    最近更新 更多