2014-07-21 62 views
1

Powershell中的“-contains”运算符需要完全匹配(无通配符)。 “ - 匹配”运算符允许通配符和部分匹配。如果我想对可能的匹配列表执行部分/通配符匹配,那么我应该如何执行此操作?使用Powershell中的另一个列表在列表中搜索部分匹配

例如:

$my_match_list = @("Going","Coming","Leaving","Entering") 
$my_strings_list = @("Going home", "Coming over", "Leaving the house", "Entering a competition") 

“走出去”将-match“回家”,但$ my_strings_list不会-contains“走出去” 现在我工作围绕这通过循环,但它不”看起来应该是最好的方式:

foreach($i in $my_strings_list){ 
    foreach($y in $my_match_list){ 
    if($i -match $y){ 
    do.something 
    } 
    } 
} 

我应该如何解决这个问题? 对于具体的任务,我实际上是为所有匹配1个描述的用户查询一个大的AD数据库。我希望它看起来尽可能整洁。我有类似的东西:

$myVar = get-aduser -filter {blah -ne blah} -properties description | ?{$_.description -match "blah1" -or (etcetcetc) 

但它成为过滤器字符串中可能匹配的一个可怕的长长的清单。然后我把所有东西都放到一个变量中,然后处理出我想要的实际匹配。但看起来我应该能够以更少的线路完成任务。也许只有1长的正则表达式字符串,并将其放入过滤器?

|?{$_.description -match "something|something|something|something" 

编辑:正则表达式可能是最短的我猜:

$my_match_list = "going|coming|leaving|entering" 
foreach($i in $my_strings_list){if($i -match $my_match_list){do.something}} 

所以:

get-aduser -filter {blah -ne blah} -properties description | ?{$_.description -match $my_match_list} 

我宁愿更多的东西,如“获取,等等等等| {$ _描述? $ my_match_list},因为它更容易添加东西比把它们添加到一个正则表达式的列表。

+1

然后将它们添加到列表中,并转换为正则表达式。 '$ filter =“($($ ArrayOfStuff -join”|“))”'将@(“Bob”,“June”,“Michael”)'变成'“(Bob | June | Michael)”' – TheMadTechnician

+0

是天才。谢谢。 – BSAFH

回答

2
$my_match_list = @("Going","Coming","Leaving","Entering") 
$my_strings_list = @("Going home", "Coming over", "Leaving the house", "Entering a competition") 

[regex]$Match_regex = ‘(‘ + (($my_match_list |foreach {[regex]::escape($_)}) –join “|”) + ‘)’ 

$my_strings_list -match $Match_regex 

Going home 
Coming over 
Leaving the house 
Entering a competition 

http://blogs.technet.com/b/heyscriptingguy/archive/2011/02/18/speed-up-array-comparisons-in-powershell-with-a-runtime-regex.aspx

相关问题