简体   繁体   English

在`for`循环上使用`&&`的两个命令的双管道语句(批处理脚本)

[英]Double-pipe statement with two commands using the `&&` on a `for` loop (batch script)

Based on answers and comments from this question , I cannot understand how to add a double-pipe || 根据该问题的 答案和评论,我无法理解如何添加双管道|| statement with two commands using the && on a for loop . for循环上使用&&和两个命令的语句 Consider the following example taken from here : 考虑取自下面的例子在这里

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

If I try 如果我尝试

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a" || echo Error while getting datetime. >> %someoutputfile% && GOTO endthis

I get a Unexpected && error. 我收到Unexpected &&错误。 I tried adding parenthesis around the each command after the || 我尝试在||之后在每个命令周围添加括号。 but they too give Unexpected ) similar errors. 但它们也给Unexpected )类似的错误。

Can someone explain what I am doing wrong? 有人可以解释我在做什么错吗? Should I put the || 我应该把|| commands before the do set "dt=%%a" or something? 之前的命令do set "dt=%%a"或其他内容?

You may also use this approach: 您也可以使用这种方法:

(for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a") || rem

if errorlevel 1 echo Error while getting datetime. >> %someoutputfile% & GOTO endthis

This method is fully described below Exit Code management at this answer . 此方法在此答案的 退出代码管理中进行了详细说明

Here's a working example: 这是一个工作示例:

@ echo off

for /f "tokens=2 delims==" %%a in ('WMIC OS Get LocalDateTime /value') do (
    set dt=%%a && (
        echo Local Data Time: "%dt%"
    ) || (
        echo Error while getting datetime.
        goto ERROR
    )
)

echo Exiting...
goto END

:ERROR
echo Terminating...

:END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM