我已经将头撞在墙上几个小时了,正在寻找帮助。为了简化我的问题,我有两个数组,一个数组包含通配符,另一个数组使用这些通配符:
$WildCardArray = @("RED-*.htm", "*.yellow", "BLUE!.txt", "*.green", "*.purple")
$SpelledOutArray = @("RED-123.htm", "456.yellow", "BLUE!.txt", "789.green", "purple.102", "orange.abc")
我无法让PowerShell识别出这些匹配项。
我的最终目标是得到一个输出,告诉我Purple.102和orange.abc不在$ WildCardArray中。
似乎 super 简单!我尝试过的一些方法:
$WildCardArray = @("RED-*.htm", "*.yellow", "BLUE!.txt", "*.green", "*.purple")
$SpelledOutArray = @("RED-123.htm", "456.yellow", "BLUE!.txt", "789.green", "purple.102", "orange.abc")
foreach($Item in $SpelledOutArray)
{
$item | where {$wildcardarray -contains $item}
}
结果得到BLUE!.txt,因为这是我的控件,没有通配符。如果将其更改为-notcontains,则将获得除BLUE之外的所有结果。我试过包含,匹配,等于,类似以及它们的所有对立,比较对象,但没有任何效果。我没有错误,只是没有得到预期的结果
我尝试用[a-zA-Z]和其他组合替换“*”,但实际上是替换了它,而不是通配符。我不确定自己在做什么错... PSVersion 5.1 Win 10
有谁知道为什么喜欢/匹配/包含的逻辑不起作用,我能做什么使其起作用?它不必很漂亮,只需要工作即可
最佳答案
banging my head against a wall for hours [..] Seems super simple!
这可能暗示它并非 super 简单。您正在尝试交叉匹配两个列表:红色到红色,黄色,蓝色...。然后蓝色到红色,黄色,蓝色...然后绿色到红色,黄色,蓝色...。30个比较但您只有发生5个循环。
你需要更多。
$WildCardArray = @("RED-*.htm", "*.yellow", "BLUE!.txt", "*.green", "*.purple")
$SpelledOutArray = @("RED-123.htm", "456.yellow", "BLUE!.txt", "789.green", "purple.102", "orange.abc")
# Loop once over the spelled out items
foreach($Item in $SpelledOutArray)
{
# for each one, loop over the entire WildCard array and check for matches
$WildCardMatches = foreach ($WildCard in $WildCardArray)
{
if ($item -like $WildCard) {
$Item
}
}
# Now see if there were any wildcard matches for this SpelledOut Item or not
if (-not $WildCardMatches)
{
$Item
}
}
并且WildCardArray上的内部循环可以成为过滤器,但是您必须过滤数组,而不是像代码那样过滤单个项。
$WildCardArray = @("RED-*.htm", "*.yellow", "BLUE!.txt", "*.green", "*.purple")
$SpelledOutArray = @("RED-123.htm", "456.yellow", "BLUE!.txt", "789.green", "purple.102", "orange.abc")
foreach($Item in $SpelledOutArray)
{
$WildCardMatches = $wildcardarray | Where { $item -like $_ }
if (-not $WildCardMatches)
{
$Item
}
}
而且我想如果需要的话,您可以将其混入一个不清楚的双向过滤器中。
$WildCardArray = @("RED-*.htm", "*.yellow", "BLUE!.txt", "*.green", "*.purple")
$SpelledOutArray = @("RED-123.htm", "456.yellow", "BLUE!.txt", "789.green", "purple.102", "orange.abc")
$SpelledOutArray |Where {$item=$_; -not ($WildCardArray |Where {$item -like $_}) }
关于arrays - 匹配数组时Powershell使用通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41107211/