Looping Batch Script Recipe

The following procedure creates and executes a looping script that executes a command with output to a file and a sleep in between each execution:

  1. Create a file named diagscript.sh replacing the command after the CHANGEME comment, and, if necessary, the sleep time:
    @echo off
    SETLOCAL ENABLEDELAYEDEXPANSION
    
    :loop
    
    echo [%date% %time%] Executing iteration
    
    :: CHANGEME: Change the `tasklist` command to your desired command:
    tasklist
    
    :: Change the sleep time (in seconds) as needed:
    timeout /t 30 > NUL
    
    goto loop
  2. Open a command prompt and change directory to where you would like to store the script output; for example:
    cd %TEMP%
  3. Manually confirm the looped command exists and works (as some versions support different flags). Using the example command above:
    tasklist
  4. Execute the script and redirect output to a file, replacing C:\ with the directory of the script:
    C:\diagscript.bat > diag_%computername%.txt 2>&1
  5. Monitor that the script output does not exhaust disk
  6. When you are ready to stop the script, kill it by closing the command prompt window (Ctrl+C may not reliably work)
  7. Upload diag*.txt and any other relevant logs