wittich
wittich

Reputation: 2311

CMD/Batch Prompting for Input loop without goto command

I have a loop scanning for the files of a folder and I want to ask for each file if it should be moved or not. As I am already in that loop I can't use goto commands.

How can I prompt a input loop (yes / no) without using a goto command?

@echo off
setlocal enableDelayedExpansion

FOR %%a in (*.jpg) DO (

:: ask
set /p Input="Should !a! be moved? (yes/no)"

if %Input% == 'yes' (
MOVE !a! path/
)

if %Input% == 'no' (
:: just move on in loop
)

:: if not yes or no goback to ask

)

Upvotes: 0

Views: 1879

Answers (5)

Stephan
Stephan

Reputation: 56180

Another alternative is the choice command, which accepts only predefined keystrokes, so there is no additional need to check for valid options:

@echo off
setlocal enableDelayedExpansion
FOR %%a in (*.jpg) DO (
  choice /C YN /M "Should %%a be moved? "
  if %errorlevel% == 2 echo not moving
  if %errorlevel% == 1 move "%%a" path\
)

for more information, use choice /?

(Note: choice is not available in some windows versions)

Upvotes: 1

Dlanod Kcud
Dlanod Kcud

Reputation: 537

You can't do this directly because of the way the FOR loop is processed. You can do it indirectly though. Look for the call-command:

echo off
setlocal

for %%i in (*) do
    call :Bar %%i
goto :eof

:Bar  
@echo %1 
goto :eof 


:eof    
endlocal         

Upvotes: 2

Bill_Stewart
Bill_Stewart

Reputation: 24555

PowerShell can save you a lot of trouble...

get-childitem "*.jpg" | foreach-object {
  move-item $_ "path/" -confirm
}

Upvotes: 2

Aacini
Aacini

Reputation: 67216

@echo off
setlocal enableDelayedExpansion

FOR %%a in (*.jpg) DO (

   rem ask
   set /p Input="Should %%a be moved? (yes/no)"

   if "!Input!" == "yes" (
      MOVE %%a path/
   )

)

Upvotes: 1

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "input="    
    for %%a in (*.jpg) do (
        cmd /v /e /q /c "for /l %%z in (0) do (set /p "input=Should %%a be moved (yes/no^)? " & if /i !input!==yes (exit 0) else if /i !input!==no (exit 1))"
        if not errorlevel 1 (
            echo move "%%a" "c:\somewhere"
        ) else (
            echo skipping %%a
        )
    )

A new cmd instance is started for each file to retrieve user input. This input is validated and errolevel is used to return user selection to parent code.

While it is not usually a good idea start a new process for each iteration of a loop, in this case, as the user interaction is required for each file, the time needed to start the new cmd instance can be ignored as the user itself will require a lot more time.

move commands are only echoed to console. If the behaviour is correct, remove the echo that prefixes the move command.

Upvotes: 3

Related Questions