Windows Batch - 检查一个命令变量是否出现在另一个命令变量中

时间:2017-02-22 09:35:15

标签: windows batch-file variables

我正在努力获得所需的输出。

我使用2个命令在多个设备上获取设备上的2个变量。我不确定如何交叉引用这些以获得我想要的输出。我正在尝试查看 DEVPACKAGE 的任何内容是否出现在的内容中,如果它们没有出现在中则返回错误。我假设它与[Windows Batch: How to set the output of one command as a variable and use it in another command?类似,但我看不出如何将它应用于我当前的变量。

据我所知,我的一些方法可能很粗糙。我只是认真研究一周的批处理文件构建。

DEVPACKAGEPackage和尝试输出如下:

::Global
@echo off

set AAPT=tools\aapt.exe
set GREP=tools\grep.exe
set CUT=tools\cut.exe

:: Check Gold Build applications
cls
@echo.
@echo ------------------------ CHECK APPLICATIONS INSTALLED --------------------------

SETLOCAL ENABLEDELAYEDEXPANSION
::EXTRACT PACKAGENAME FROM APK
FOR /F "tokens=1,2 skip=1" %%N IN ('adb devices') DO (
    SET IS_DEV=%%O
    if "!IS_DEV!" == "device" (
        SET SERIAL=%%N
        for /f "delims=" %%P in ('dir /b ^"APKs\*.apk^"') do (
            SET APK=%%P
            for /f "tokens=1 delims=" %%Q in ('%AAPT% d badging APKs\!APK! ^| !GREP! "package: name=" ^| !CUT! -d' -f2') do (
                set package=%%Q
                if "!package!" == "" set package=Unknown (
                )
            )
        )
    )
)
::EXTRACT INSTALLED PACKAGENAME
FOR /F "tokens=1,2 skip=1" %%R IN ('adb devices') DO (
    if "!IS_DEV!" == "device" (
        FOR /F "tokens=1 delims=" %%U IN ('adb shell "pm list packages" ^| !CUT! -f 2 -d ":"^') DO (
        SET DEVPACKAGE=%%U
                )
            )
        )
    )
)
::CHECK IF INSTALLED APPEARS IN PACKAGENAME FROM APK FOLDER
FOR /F "tokens=1,2 skip=1" %%V IN ('adb devices') DO (
    if "!IS_DEV!" == "device" (
        for /f "delims=" %%W in ('dir /b ^"APKs\*.apk^"') do (
            IF !DEVPACKAGE! NEQ !package! (
                echo Device !SERIAL! does not have !package! installed
                ) else (
                echo Device !SERIAL! has all APKs installed correctly
                    )
                )
            )
        )
    )
)
ENDLOCAL
@pause

我的变量输出类似于:

------------------------ CHECK APPLICATIONS INSTALLED --------------------------

Device <SERIAL1> does not have <APK2> installed
Device <SERIAL3> does not have <APK1> installed
Device <SERIAL22> does not have <APK7> installed

Press any key to continue . . .

非常感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

更简单的方法:

setlocal enableDelayedExpansion
set "DEVPACKAGE_=!DEVPACKAGE:"=""!"
echo !package!|find "!DEVPACKAGE_!" >nul 2>nul && (
   echo it is contained
)||(
   echo it is NOT contained
)

需要临时变量DEVPACKAGE_才能使"加倍,因此如果字符串包含它,将由FIND命令正确处理。

您也可以使用cmd internals命令执行此操作:

setlocal enableDelayedExpasion
if "%package%" equ "!package:%DEVPACKAGE%=!" (
  echo it is NOT contained
) else (
  echo it is contained
)

理论上,第二种方法应该更快,但有更多的角色可以打破它。