You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断值是否匹配含通配符的PowerShell数组并避免重复添加

PowerShell 通配符数组匹配问题解决

问题场景

你定义了包含通配符的排除数组:

$ArrVar_ASP=@("Adobe*","UXP WebView Support")

当前$pre.DisplayName的值为Adobe Acrobat (64-bit),使用以下语句时,无法识别通配符匹配,导致本该排除的项被加入目标数组:

If ($($pre.DisplayName) -notin $ArrVar_ASP) {$ArrVar_ASPPreinstalltemp+=$pre}

解决方案

-notin是精确字符串匹配,不支持通配符解析。要实现通配符匹配判断,需要用-like运算符遍历数组中的每个模式,检查是否存在匹配项。以下是两种可行写法:

写法一:使用管道与Where-Object

# 检查是否存在匹配的通配符模式
$hasMatch = $ArrVar_ASP | Where-Object { $pre.DisplayName -like $_ }

# 无匹配时才添加到目标数组
if (-not $hasMatch) {
    $ArrVar_ASPPreinstalltemp += $pre
}

写法二:使用循环遍历

$shouldAdd = $true
foreach ($pattern in $ArrVar_ASP) {
    if ($pre.DisplayName -like $pattern) {
        $shouldAdd = $false
        break # 找到匹配后立即终止循环,提升效率
    }
}

if ($shouldAdd) {
    $ArrVar_ASPPreinstalltemp += $pre
}

原因说明

PowerShell中的-in/-notin运算符仅做精确字符串比对,不会解析通配符;而-like才是专门支持通配符(*、?等)匹配的运算符,因此必须通过遍历数组中的每个通配符规则,逐一验证当前值是否符合规则。

内容的提问来源于stack exchange,提问作者François Racine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 14:10:56