How to supply console input ( yes / no ) as part of batch file on Windows.

后端 未结 6 882
春和景丽
春和景丽 2020-12-08 08:33

I am writing a simple batch file (remove.bat) to remove a directory and all its subdirectories. The file contains the following command-

rmdir /S modules


        
相关标签:
6条回答
  • 2020-12-08 08:55

    If you are not dealing with a windows with a english/us locale you might need to retrieve the answers needed for your machine:

    @echo off
    
    setlocal
    
    set "ans_yes="
    set "ans_no="
    set "ans_all="
    
    copy /y nul # >nul
    
    for /f "tokens=2-7 delims=[(/)]" %%a in ( '
        copy /-y nul # ^<nul
    ' ) do if not defined ans_yes if "%%~e" == "" (
        set "ans_yes=%%~a"
        set "ans_no=%%~b"
        set "ans_all=%%~c"
    ) else (
        set "ans_yes=%%~a"
        set "ans_no=%%~c"
        set "ans_all=%%~e"
    )
    
    del /q #
    
    set "ans_yes=%ans_yes: =%"
    set "ans_no=%ans_no: =%"
    set "ans_all=%ans_all: =%"
    
    set "ans_y=%ans_yes:~0,1%"
    set "ans_n=%ans_no:~0,1%"
    set "ans_a=%ans_all:~0,1%"
    
    endlocal & (
        set "ans_y=%ans_y%"
        set "ans_n=%ans_n%"
        set "ans_a=%ans_a%"
    )
    
    echo %ans_y%|rmdir /s modules
    
    0 讨论(0)
  • 2020-12-08 08:57

    Do rmdir /S for deleting a non-empty directory and do rmdir /Q for not prompting. Combine to rmdir /S /Q for quietly delete non-empty directories.

    0 讨论(0)
  • 2020-12-08 09:05

    As others have pointed out, you should use the /Q option. But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply ECHO the needed response and pipe the value into the command.

    echo y|rmdir /s modules
    

    I recommend using the /Q option instead, but the pipe technique might be important if you ever run into a command that does not provide an option to suppress confirmation messages.

    0 讨论(0)
  • 2020-12-08 09:09

    You can do

    rmdir /Q
    

    Q is for quiet

    0 讨论(0)
  • 2020-12-08 09:16

    Use rmdir /S /Q modules

    /Q suppresses the confirmation prompt.

    0 讨论(0)
  • 2020-12-08 09:18

    I just want to add that, although not applicable to Rmdir, a force switch may also be the solution in some cases. So in a general sense you should look at your command switches for /f, /q, or some variant thereof (for example, Netdom RenameComputer uses /Force, not /f).

    The echo pipe is a neat trick and very useful to keep around since you wont always find an appropriate switch. For instance, I think it's the only way to bypass this Y/N prompt...

    Echo y|NETDOM COMPUTERNAME WorkComp /Add:Work-Comp
    

    Link to nearly identical StackOverflow post

    0 讨论(0)
提交回复
热议问题