Home > Software design >  Powershell: Run a BAT from another BAT and Supply Variables
Powershell: Run a BAT from another BAT and Supply Variables

Time:01-06

Super short version: I've got a massive BAT file that I'm looking to make into a smaller series of child-BAT files I can run from a single parent-BAT file while supplying variables.

Confused?

Example: One thing the main BAT file I have now does is it sweeps a number of different locations for debris files and folders, and deletes them. It's identical verbiage for each sweep, the only thing that changes is the folder.

So what I'd like to do is construct a BAT file that does something like this:

Run Clear_Debris.bat
$searchdrive = "H:\"

Run Clear_Debris.bat
$searchdrive = "W:\"

Run Drive_Migration.bat
$sourcedrive = "H:\"
$destdrive = "W:\"

And so on. Basically, a single BAT can invoke other BATs (which don't have values specified for variables), and specify what those BATs should use as values for their variables. That way I can break out all the individual functions into their own BAT files that I can run individually when I need to, or else when I need to make a change to one of the routines, I only have to do it in one place instead of more than one.

Is this possible?

CodePudding user response:

  • Place all your .bat (.cmd) files in the same folder.

  • Call each subordinate batch file using the call command, to ensure that execution continues in the main batch file.

  • Use path prefix %~dp0 to ensure that the subordinate batch files can be located alongside the main batch file, irrespective of what the working directory is (%~dp0 expands to the full path of the directory in which the executing batch file is located, always followed by a \ - run for /? for details)

    • If, instead, you want to place the subordinate batch files in a subfolder of the main batch file instead, say util, simply append that subfolder's name, say %~dp0util\.
  • The subordinate batch files automatically see the main batch file's variables, though you can localize variable changes performed in the subordinate batch files with setlocal

    • However, for conceptual clarity and maintainability, consider designing your subordinate batch files to accept arguments to be passed by the main batch file on invocation, accessible in the callee as %1, %2, ...

Outline of the main batch file:

@echo off & setlocal

:: Run Clear_Debris.bat
set "searchdrive=H:\"
call "%dp0Clear_Debris.bat"

:: Run Clear_Debris.bat with a different %searchdrive% value.
set "searchdrive=W:\"
call "%~dp0Clear_Debris.bat"

:: ...

You may also want to act on the %ERRORLEVEL% value after each call to check if a subordinate batch file reported an error.

  • Related