-1

I have a program that creates .bat files to c:\temp. I need to create a script that runs each .bat file inside c:\temp and moves them to c:\temp\backup after a successful execution.

How can i achieve this? Thank you

  • Write your commands in a plain text file, give the file a `.bat`, or better a `.cmd`, extension and run it. This site isn't writing it for you, however there's a very good search facility at he top of each page, to assist you. – Compo Aug 24 '20 at 15:10

1 Answers1

0

The following code can be a good starting point.

  1. Use the for loop to enumerate the files with .bat extension in the given directory.
  2. Use the call command to execute.
  3. Use the move command to move the file to other directory.

Update: As suggested in the comments, I added a basic error checking if the call command succeeded and only in the case of success, I am moving the bat file.

    @echo off
    set myDir=C:\temp\bats
    set doneDir=C:\temp\bats\done\

    md %doneDir%
    for %%I in ("%myDir%\*.bat") do (
       call %%I
       if %ERRORLEVEL% == 1 (          
            move %%I %doneDir%
       ) else (
            echo "error moving - %errorlevel%"
        )
    )
EylM
  • 5,967
  • 2
  • 16
  • 28
  • 1
    You missed the `after a **successful** execution` part... – Stephan Aug 24 '20 at 15:42
  • I stated it's a good starting point. What else do you recommend? – EylM Aug 24 '20 at 15:48
  • 2
    change `move...` to `if not errorlevel 1 move...` – Stephan Aug 24 '20 at 16:12
  • @Stephan - this makes sense. I edited the code. – EylM Aug 24 '20 at 16:21
  • shorter `for %%I in ("%myDir%\*.bat") do call %%I && move /Y "%%I" "%donedir% || echo unable to move %%i` – Gerhard Aug 24 '20 at 16:51
  • You'd need [delayed expansion](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected/30284028#30284028) to make that work (that's why I suggested `if not errorlevel`, not `if %errorlevel% ==` (or rather `if !errorlevel! ==` here) – Stephan Aug 24 '20 at 19:40