Search code examples
batch-fileiisdelayapplication-poolrecycle

Recycle all app pools with a .bat file with a delay between each one


I would like to have a delay between each recycled app pool so the CPU doesn't get high. Below is my current .bat file that recycles all my app pools at once. How can I add a delay between each one before the other gets executed?

%windir%\system32\inetsrv\appcmd list wp /xml | %windir%\system32\inetsrv\appcmd recycle apppool /in

Here is my output per a answer

<?xml version="1.0" encoding="UTF-8"?>

<appcmd>

    <WP WP.NAME="8476" APPPOOL.NAME="8476.com" />

    <WP WP.NAME="11636" APPPOOL.NAME="11636.com" />

    <WP WP.NAME="8868" APPPOOL.NAME="8868.com" />

    <WP WP.NAME="6180" APPPOOL.NAME="6180.com" />

    <WP WP.NAME="5636" APPPOOL.NAME="5636.com" />

    <WP WP.NAME="12616" APPPOOL.NAME="12616.com" />

    <WP WP.NAME="7472" APPPOOL.NAME="7472.com" />

    <WP WP.NAME="1668" APPPOOL.NAME="1668.com" />

    <WP WP.NAME="9608" APPPOOL.NAME="9608.com" />

    <WP WP.NAME="12480" APPPOOL.NAME="12480.com" />

</appcmd>

Solution

  • EDIT 2022/08/04: New code based on new posted data

    The appcmd list wp /xml command outputs one XML file that contains several WP sections, one for each app pool, in this format:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <appcmd>
    
        <WP data for pool 1 />
    
        <WP data for pool 2 />
    
        . . .
    
    </appcmd>
    

    In this way, in order to execute each app pool cmd individually, we need to create individual well-formatted XML files. The Batch file below do so:

    @echo off
    setlocal DisableDelayedExpansion
    
    rem Create the "all apps" XML output file
    %windir%\system32\inetsrv\appcmd.exe list wp /xml > appcmdXMLout.txt
    
    rem Separate "all apps" output file into individual app input file(s) and process each
    set "header="
    set "line1="
    for /F "delims=" %%a in (appcmdXMLout.txt) do (
    
       if not defined header (
          set "header=%%a"
          setlocal EnableDelayedExpansion
          > appcmdXMLin.txt echo !header!
          endlocal
       ) else if not defined line1 (
          set "line1=%%a"
          setlocal EnableDelayedExpansion
          >> appcmdXMLin.txt echo !line1!
          endlocal
       ) else if "%%a" neq "</appcmd>" (
          rem One appcmd completed: process it
          (
          set /P "=%%a" < NUL
          echo/
          echo ^</appcmd^>
          ) >> appcmdXMLin.txt
    
          %windir%\system32\inetsrv\appcmd.exe recycle apppool /in < appcmdXMLin.txt
          timeout /T 5 > NUL
    
          setlocal EnableDelayedExpansion
          (
          echo !header!
          echo !line1!
          ) > appcmdXMLin.txt
          endlocal
    
       )
    
    )
    
    del appcmdXMLout.txt appcmdXMLin.txt