How do I pass parameters to a batch file?

John Savill

January 8, 2000

2 Min Read
ITPro Today logo in a gray background | ITPro Today

Related:  How to parse a batch parameter

A. When you call a batch file, you can enter data after the command that the batch file refers to as %1, %2, etc. For example, in the batch file hello.bat, the following command

@echo hello %1 boy

would output

hello john boy

if you called it as

hello john

The following table outlines how you can modify the passed parameter.

ParameterDescription%1The normal parameter.%~f1Expands %1 to a fully qualified pathname. If you passed only a filename from the current directory, this parameter would also expand to the drive or directory.%~d1Extracts the drive letter from %1.%~p1Extracts the path from %1.%~n1Extracts the filename from %1, without the extension.%~x1Extracts the file extension from %1.%~s1Changes the n and x options’ meanings to reference the short name. You would therefore use %~sn1 for the short filename and %~sx1 for the short extension.

The following table shows how you can combine some of the parameters.

ParameterDescription%~dp1Expands %1 to a drive letter and path only.%~sp1For short path.%~nx1Expands %1 to a filename and extension only.

To see all the parameters in action, put them into the batch file testing.bat, as follows.

@echo offecho fully qualified name %~f1echo drive %~d1echo path %~p1echo filename %~n1echo file extension %~x1echo short filename %~sn1echo short file extension %~sx1echo drive and directory %~dp1echo filename and extension %~nx1

Then, run the file with a long filename. For example, the batch file run on the file c:templongfilename.long would produce the following output.

fully qualified name c:TEMPlongfilename.longdrive c:path TEMPfilename longfilenamefile extension .longshort filename LONGFI~1short file extension .LONdrive and directory c:TEMPfilename and extension longfilename.long

This method also works on the second and subsequent parameters. You simply substitute the parameter for 1 (e.g., %~f2 for the second parameter’s fully qualified path name).

Related:  Using URLs in Batch Files

The %0 parameter in a batch file holds information about the file when it runs and indicates which command extensions you can use with the file (e.g., %~dp0 gives the batch file’s drive and path).

Learn more:  How many parameters can I pass to batch file?

About the Author

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like