次の方法で共有


Using %0 inside the batch file to get the file info

Ok, writing a command/batch file to automate tasks in Windows may be outdated already, but sometimes it is quicker and easier to write and call the batch file to achieve what we want. Pretty often I want to display the the batch filename which being called (i.e. to display it on the Usage section), or sometimes I want to refer to other files located in the directory name where the batch file located, but the file is called from another directory (hence can't use current directory). I believe most of you know this trick already, but in case you forgot already. The key is to use %0 and its variation. It's easier to learn from example, so here is a sample batch file called bar.cmd in c:\foo, contains following scripts:

@echo.

@echo %%0 = %0

@echo %%~f0 = %~f0

@echo %%~d0 = %~d0

@echo %%~p0 = %~p0

@echo %%~n0 = %~n0

@echo %%~x0 = %~x0

If we run the batch file from the Command window, it will produce following output:
 

C:\>foo\bar.cmd

 

%0 = foo\bar.cmd

%~f0 = C:\foo\bar.cmd

%~d0 = C:

%~p0 = \foo\

%~n0 = bar

%~x0 = .cmd

As we can see above, %0 will return the string we invoke from the command shell, which then we can add another modifier to it, such as: ~f to get the file full path, ~d to get the drive name, ~p to get the folder path name (minus drive name), ~n to get the file name without extension name, and ~x to get the extension name only. We also can combine those modifiers, so for example: %~dpnx0 will actually give us the same result as %~f0

Comments