Use Modifiers to Expand or Shorten a Script's Name on the Fly
In Windows shell scripts, you can use %0 to obtain the name of the script being executed. By using modifiers, you can easily obtain a variation of that name, such as the fully qualified path name or just the file extension.
March 27, 2007
In "An Easy Way to Prevent Runaway Scripts" (http://www.windowsitpro.com/Articles/ArticleID/95196/95196.html), Dick Lewis discusses how to prevent runaway Windows shell scripts by adding a .txt extension to a script's filename after executing the script. For example, if a script is named MyScript.bat, you'd rename the script MyScript.bat.txt. Adding a .txt extension removes the danger of accidental launches but lets you keep the script's original filename and keeps the code intact for future use. To use the script again, you just remove the .txt extension. Dick notes that you can add the following one-line command to the end of a script to prompt the script to automatically rename itself:
Move %0 %0.txt
By using %0 as the source parameter and %0.txt as the destination parameter, you're appending the .txt extension to the filename while "moving" the script to the same location. (In Windows shell scripts, %0 is the name of the script being executed.)
Dick warns that when you run the script, you must launch it with the extension specified. For example, you need to type
MyScript.bat
on the command line. Typing only
MyScript
will cause the Move command to not work correctly because the command processor executes that command as
Move MyScript MyScript.txt
Thus, the script will now be named MyScript.txt instead of MyScript.bat.txt.
You can eliminate the restriction of having to include the extension when you launch the script by using a slightly different version of the Move command:
Move "%~f0" "%~f0.txt"
Adding the ~f modifier tells the command processor to expand the script's name to a fully qualified path name before adding the .txt extension. You can also use this technique with the Rename command
Rename “%~f0” “%~nx0.txt”
In this case, ~nx modifier tells the command processor to expand the script's name to a filename and extension before adding the .txt extension.
Listing 1 contains a script that demonstrates other ways you can modify the script's name. After you download this script from the Scripting Pro VIP Web site, simply launch it from the command line. In addition, you'll find more information about modifiers in the "Manipulating Command-Line Parameters" sidebar (http://www.windowsitpro.com/articles/articleid/46132/Manipulating_CommandLine_Parameters.html), which is part of the article "A New, Improved Stab at File Ownership" (June 2005, InstantDoc ID 46131). You can also check out the "Using batch parameters" Web page at http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true.
—Logan Lam
About the Author
You May Also Like