首页 > 解决方案 > 批处理文件设置命令在 if 语句中不起作用

问题描述

对于我的一生,我无法弄清楚为什么以下提示在语句set中时不起作用:if

@echo off

REM :askdeletecsvs
if exist *.csv (
    echo Warning! All files in the scripts folder that have the "CSV" extension will be deleted!
    echo Answering "n" will continue the script without deleting the CSVs.
    set /p ASKDELETE=Delete CSVs? (y/n): 
REM     
REM     if ( /i %ASKDELETE% equ "y" goto :deletecsvs )
REM     if ( /i %ASKDELETE% equ "n" goto :runscripts )
REM     goto :askdeletecsvs
)

当我在 cmd 窗口上方运行批处理文件时,它会打开然后快速关闭。如果我将该set行移到语句之外,if则提示将按预期显示。(运行 bat 文件的文件夹中csvs)

我错过了什么?

标签: batch-fileif-statementcmd

解决方案


首先,您使用了一个右括号,该括号过早地结束了您的左If括号。

我建议扭转这种想法:

If Not Exist *.csv GoTo runscripts

Echo Warning!
Echo All files in the scripts folder that have the "CSV" extension will be deleted!
Echo Answering "N" will continue the script without deleting the CSVs.
Choice /M "Delete CSVs" 
If ErrorLevel 2 GoTo runscripts

:deletecsvs
Del /F /Q /A "PathTo\scripts\*.csv"
GoTo :EOF

:runscripts

您可以GoTo :EOF根据需要更改为相关的有效标签,如果您想继续使用,可以将其删除:runscripts。如果批处理文件从脚本目录运行,您也可以替换PathTo\scripts\为,或者如果当前目录包含这些文件,则删除。(注意当前目录和批处理文件路径不一定相同)%~dp0PathTo\scripts\


推荐阅读