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

PowerShell数组字符串子串匹配问题:代码逻辑错误排查

PowerShell子串匹配问题修正

你的代码核心问题是**-like的匹配逻辑方向错误**:
你需要判断$comparestrings中的字符串是否是$AdGroup元素的子串(即长字符串包含短字符串),但原代码写的是$dev -like "*$item*"——这是在检查短字符串是否包含长字符串,显然不可能匹配成功。

修正后的代码如下:

$AdGroup = "cn-sg-robot-platform","cn-sg-capture-platform","cn-sg-easy-platform","cn-sg-content-platform"
$comparestrings = "sg-robot-platform" , "sg-easy-platform"

foreach ($item in $AdGroup) {
    $matchFound = $false
    foreach ($dev in $comparestrings) {
        # 反转匹配方向:检查$item是否包含$dev
        if ($item -like "*$dev*") {
            $matchFound = $true
            Write-Host "Match found for $item"
            break
        }
    }
    if (-not $matchFound) {
        Write-Host "No match found for $item"
    }
}

运行后会输出:

Match found for cn-sg-robot-platform
No match found for cn-sg-capture-platform
Match found for cn-sg-easy-platform
No match found for cn-sg-content-platform

你也可以用更简洁的写法简化嵌套循环:

$AdGroup | ForEach-Object {
    $currentItem = $_
    if ($comparestrings | Where-Object { $currentItem -like "*$_*" }) {
        Write-Host "Match found for $currentItem"
    }
    else {
        Write-Host "No match found for $currentItem"
    }
}

内容的提问来源于stack exchange,提问作者Varun Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 02:37:19