John's Computer Journal: Batch function library loader

Saturday, May 19, 2007

Batch function library loader

I've put together a few functions that I find useful when doing batch scripting. I've attached the library of functions bellow. Included in the library are functions for multi-line out, file-prepending, and unsetting environment variables.


call function :[function_name] [function_parameters]

[function_name]       - name of the function.
[function_parameters] - arguments to pass to the function.

Read the function documentation within the function.bat file for further information on variables specific to each function. Examples of each function included with the attached file are provided below.


call function :unset path temp tmp username

The above example executes the function unset with the parameters: path, temp, tmp, and username. After executing the unset function each of the environment variables path, temp, tmp, and username will no longer exist.

call function :prepend history 1st I did this
call function :prepend history 2nd I did this

The above example executes the function prepend twice with two parameters: history and a string. After executing the prepend function the file named history will have the line: "2nd I did this" (without the quotes) as the first line of the file and the line: "1st I did this" (without the quotes) as the second line of the file.

goto output

Hello %username%,
Do you know the ^%TIME^%?


call function :out %0 output  

The above example builds a multi-line output and executes the function out with two parameters: the current filename and the target output. Notice the % symbols are escaped for TIME to prevent out from expanding the %TIME% variable. After executing the out function the following will appear on the display:

Hello John,
Do you know the %TIME%? 

Note: the results of the out function can also be redirected to a file by appending the > operator.

Adding Functions

New functions can be added to the function library by adding a label and goto :EOF pair where the label is the name of the new function. For example the following code will add the hello function which will simply display Hello %1 where %1 is the first argument passed to hello.

    echo Hello %1
goto :EOF

After adding the above code to the function.bat file and typing:

call function :hello World!
call function :hello %username%!

will display:

Hello World!
Hello John!
A good collection of functions ready to be copied and pasted directly into the function file can be found at Ritchie Lawrence's Batch Function Library.



No comments: