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

Windows .bat脚本ADB设备检测异常:字符串包含判断失效求助

问题排查与解决方案

首先,你的脚本始终跳转到step2的核心原因出在FOR /F循环的变量赋值逻辑上:

当你执行FOR /F "tokens=*" %%g IN ('adb devices') DO SET result=%%g时,循环会逐行读取adb devices的输出,但每次都会把result覆盖成当前行的内容,最终result只会保留输出的最后一行。而adb devices的标准输出结构是这样的:

List of devices attached
61047ce9 device

(末尾会有一个空行),所以最终result的值是空字符串。这时执行echo %result% | FINDSTR /I "device"自然找不到匹配,触发ERRORLEVEL 1,脚本就会跳转到step2。

两种修复方案

方案1:直接过滤并检查设备输出(推荐)

不需要额外存储变量,直接通过管道过滤掉表头行,再检查是否存在有效设备:

@echo off
@echo Plug in ONE VR headset and enable USB debugging on the device
@echo Press any button to continue
PAUSE
:step0
CD /d C:\Users\alexq\AppData\Local\Android\Sdk\platform-tools
adb kill-server
adb start-server
:step1
:: 过滤掉表头行,检查是否有包含"device"的有效设备行
adb devices | findstr /v "List" | findstr /I "device">nul
IF ERRORLEVEL 1 (
    GOTO step2
) ELSE (
    GOTO step3
)
:step2
echo Could not find attached device or USB debugging is not enabled
echo Check USB connection of VR headset
echo Enable USB debugging on the VR headset
echo Press any button to try again
PAUSE
GOTO step1
:step3
echo found device
rem WIP more stuff will be added
PAUSE

这里用findstr /v "List"排除了第一行的表头,只检查后面的设备行,逻辑更直接高效。

方案2:改进循环逻辑,找到匹配即标记

如果一定要用变量记录结果,可以在循环内逐行检查,一旦找到包含"device"的行就设置标记并跳出循环:

@echo off
@echo Plug in ONE VR headset and enable USB debugging on the device
@echo Press any button to continue
PAUSE
:step0
CD /d C:\Users\alexq\AppData\Local\Android\Sdk\platform-tools
adb kill-server
adb start-server
:step1
SET "device_found="  :: 初始化标记为空
FOR /F "tokens=*" %%g IN ('adb devices') DO (
    echo %%g | FINDSTR /I "device">nul
    IF NOT ERRORLEVEL 1 (
        SET "device_found=1"
        GOTO end_loop  :: 找到匹配后立即跳出循环
    )
)
:end_loop
IF NOT DEFINED device_found (
    GOTO step2
) ELSE (
    GOTO step3
)
:step2
echo Could not find attached device or USB debugging is not enabled
echo Check USB connection of VR headset
echo Enable USB debugging on the VR headset
echo Press any button to try again
PAUSE
GOTO step1
:step3
echo found device
rem WIP more stuff will be added
PAUSE

两种方案都能解决你的问题,方案1更简洁,适合你的场景。

内容的提问来源于stack exchange,提问作者Alexander Q.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:22:31