Windows 使用CMD脚本批处理进行优化

Windows 使用CMD脚本批处理进行优化,windows,batch-file,for-loop,cmd,Windows,Batch File,For Loop,Cmd,我的问题 我有以下代码: sc query %MyService%| find /I "running"> NUL if not ERRORLEVEL 1 ( for /f "delims=" %%i in ('sc query %MyService%^| find /I "running"') do ( :: do something I ) ) else ( for /f "delims=" %%i in ('sc query %MyServi

我的问题

我有以下代码:

sc query %MyService%| find /I "running"> NUL
if not ERRORLEVEL 1 (
    for /f "delims=" %%i in ('sc query  %MyService%^| find /I "running"') do (
        :: do something I
    )
) else (
   for /f "delims=" %%i in ('sc query  %MyService%^| find /I "running"') do (
        :: do something II
)
我想在不测试NUL的情况下执行此操作,并单独检查errorlevel。 这可能吗

for /f "delims=" %%i in ('rename...') do (
    :: do something I
) ELSE (
    :: do something II
   echo not file(s) renamed!
) 
我想知道是否可以使用FOR循环完成所有这些操作,因为如果是一个修改状态,比如某个重命名命令,我没有机会管理结果。。。 但是,如果重命名不产生结果,我怎么知道

II问题 我能不能只使用一个来获取最后一行,最后一个“字符串部分” 如果我有3行3个标记(字符串)


如何执行?

我只需执行一次查询并重用输出:

sc query %MyService%| find /I "running"> temp.txt
if not ERRORLEVEL 1 (
    for /f "delims=" %%i in (temp.txt) do (
        REM do something I
    )
) else (
   for /f "delims=" %%i in (temp.txt) do (
        REM do something II
)
(虽然
else
在这里似乎很无用)

注意:请不要在
for
语句中使用
。这可能会导致错误


抱歉,我不太理解您问题的其余部分

请使用find命令中缺少的结果来确定成功或失败。如果find命令没有找到搜索词“running”,则不会输出任何内容,for循环也不会执行

@echo off
call :Foo %MyService%
exit /b 0

:Foo <Service>
for /f "delims=" %%A in ('sc query "%~1" ^| find /i "running"') do (
    rem do something I
    exit /b 0
)
rem do something II
exit /b 1


下面是如何使用标准空格分隔符在第三行获取第三个令牌的示例

set "Test=echo A B C^&echo D E F^&echo G H I"
for /f "skip=2 tokens=3" %%A in ('%Test%') do echo %%A

@chepelucho Yep,这种方法只在命令逐个案例的基础上工作,其中命令的输出只是用于验证,而不是捕获以供使用。“dir”命令的目标是什么?你试过使用
dir…^吗查找/i“成功案例搜索词”
:Foo
for /f "delims=" %%A in ('rename... 2^>nul') do (
    rem do something I
    exit /b 0
)
rem do something II
exit /b 1
set "Test=echo A B C^&echo D E F^&echo G H I"
for /f "skip=2 tokens=3" %%A in ('%Test%') do echo %%A