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

PowerShell:If内嵌ForEach循环问题求助(服务匹配与退出码设置)

修正后的PowerShell脚本

你的核心问题是没有收集符合条件的服务集合,而是直接用循环变量$svc做判断——循环结束后$svc是最后一个遍历的服务对象,和是否存在匹配项无关。同时拆分路径时.是正则通配符,需要转义。以下是修正后的完整脚本:

try
{   
    # 从注册表获取服务列表
    $svclist = Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\services | ForEach-Object {Get-ItemProperty $_.PsPath}
    
    # 初始化空集合存储匹配的服务
    $matchingServices = @()

    # 遍历服务,筛选符合条件的项并收集
    ForEach ($svc in $svclist) {
        # 转义.避免正则匹配问题,拆分.exe后的内容
        $svcpath = $svc.ImagePath -split "\.exe"
        if(($svcpath[0] -like "* *") -and ($svcpath[0] -notlike '"*') -and ($svcpath[0] -notlike "\*")) {
            $svc | fl -Property DisplayName,ImagePath,PsPath
            $matchingServices += $svc
        }
    }

    # 根据匹配集合判断退出码
    if ($matchingServices.Count -gt 0) {
        Write-Host "Match"
        Write-Host "匹配到的服务数量: $($matchingServices.Count)"
        exit 1
    }
    else {
        Write-Host "No_Match"
        exit 0
    }    
}
catch {
    $errMsg = $_.Exception.Message
    Write-Error $errMsg
    exit 1
}

关键修正点:

  • 新增$matchingServices集合,专门存储所有符合条件的服务对象,确保判断逻辑基于实际匹配结果
  • 拆分路径时使用"\.exe"转义点号,避免正则表达式误匹配
  • 判断条件改为检查$matchingServices.Count是否大于0,准确反映是否存在匹配项
  • 移除无效的Return $svc.count语句(原$svc是单个对象,无Count属性,且exit会终止脚本)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:25:17