Search code examples
windowsbatch-filemethod-call

How do I use a bat file to call other bat files which are in different folders as I keep getting errors


So I am trying to write a bat file that calls 3 different bat files in 3 different locations. My CallAll batch file is saved in the location:

"C:\Users\Documents\CallAll\CallAll.bat"

This is the code in my CallAll bat file:

echo %DATE% %TIME%
call C:\Anaconda3\Scripts\activate.bat
call "C:\Users\Documents\Change\Loading.bat"
call "C:\Users\Documents\Convert\Runjob - XML.bat"
call "C:\Users\Documents\Result\RunModel.bat"
echo %DATE% %TIME%
pause

When I run the bat file, I get an error with the calling the first bat file which uses some files in that folder area:

(base) C:\Users\Documents\CallAll>java -jar standalone.jar -c Map.xml -o CSV XML
Error: Unable to access jarfile standalone.jar

Now I can see that it is trying to find this file in the location I run and not the location where it actually is but I do not know how to solve this

I tried using %~dp0 instead of the C:\Users\Documents but I did not get anywhere and I don't think I am using this correctly and I am struggling to understand how to use it even though I have looked at various posts

Could someone show and explain a method that works please if possible?

I have looked at other posts but they have not helped me nor have I understood what has been done


Solution

  • [untried]

    call :foreign "C:\Anaconda3\Scripts\activate.bat"
    ... repeat pattern
    pause
    goto :eof
    
    :foreign
    pushd "%~dp1"
    call %1
    popd
    goto :eof
    

    When you call a batch, unless you take action otherwise, any file access will be assumed to be with respect to the current directory at the time the call was made.

    The :foreign subroutine should change to the directory of the required batch (ie. make that directory current) [PUSHD] and then run the batch, then restore the original directory [POPD] and return.

    Note the goto :eof after the pause which will terminate the main batch, skipping over the subroutine.

    The goto :eof after the popd terminates the :foreign subroutine.

    :eof is defined by cmd as end of the batch file and does not have to be declared.

    See pushd /? and popd /? from the prompt for docco.