Powershell 在匹配数组时使用通配符

Nic*_*ick 1 regex arrays powershell wildcard

我已经用头撞墙好几个小时了,正在寻求帮助。为了简化我的问题,我有两个数组,一个包含通配符,另一个使用这些通配符:

$WildCardArray = @("RED-*.htm", "*.yellow", "BLUE!.txt", "*.green", "*.purple")
$SpelledOutArray = @("RED-123.htm", "456.yellow", "BLUE!.txt",  "789.green", "purple.102", "orange.abc")
Run Code Online (Sandbox Code Playgroud)

我无法让 PowerShell 识别出这些匹配。

我的最终目标是让输出告诉我 Purple.102 和 orange.abc 不在 $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)
{
$item | where {$wildcardarray -contains $item}
}
Run Code Online (Sandbox Code Playgroud)

结果我得到 BLUE!.txt 因为它是我的控件,没有通配符。如果我将其更改为 -notcontains,则会返回除 BLUE 之外的所有结果。我试过包含、匹配、等于、喜欢和它们所有的对立面、比较对象,但没有任何效果。我没有错误,只是没有得到预期的结果

我尝试用 [a-zA-Z] 和其他组合替换“*”,但它从字面上替换它,而不是作为通配符。我不确定我做错了什么...... PSVersion 5.1 Win 10

有谁知道为什么喜欢/匹配/包含不起作用背后的逻辑,我能做些什么使它起作用?它不必很漂亮,它只需要工作

Tes*_*ler 5

把我的头撞在墙上几个小时[..] 看起来超级简单!

这可能暗示它不是超级简单。你试图交叉配两个列表:红对红,黄,蓝....然后蓝色到红色,黄色,蓝色......然后绿色变为红色,黄色,蓝色......。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 
    }
}
Run Code Online (Sandbox Code Playgroud)

并且 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 
   }
}
Run Code Online (Sandbox Code Playgroud)

而且我想如果必须的话,您可以将其合并为一个不清楚的双位置过滤器。

$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 $_}) }
Run Code Online (Sandbox Code Playgroud)