Can a Windows batch file determine its own file name?

后端 未结 6 563
死守一世寂寞
死守一世寂寞 2020-12-07 11:16

Can a Windows batch file determine its own file name?

For example, if I run the batch file C:\\Temp\\myScript.bat, is there a command within myScript.bat that can de

6条回答
  •  生来不讨喜
    2020-12-07 11:49

    Bear in mind that 0 is a special case of parameter numbers inside a batch file, where 0 means this file as given on the command line.

    So if the file is myfile.bat, you could call it in several ways as follows, each of which would give you a different output from the %0 or %~0 usage:

    myfile

    myfile.bat

    mydir\myfile.bat

    c:\mydir\myfile.bat

    "c:\mydir\myfile.bat"

    All of the above are legal calls if you call it from the correct relative place to the directory in which it exists. %~0 strips the quotes from the last example, whereas %0 does not.

    Because these all give different results, %0 and %~0 are very unlikely to be what you actually want to use.

    Here's a batch file to illustrate:

    @echo Full path and filename: %~f0
    @echo Drive: %~d0
    @echo Path: %~p0
    @echo Drive and path: %~dp0
    @echo Filename without extension: %~n0
    @echo Filename with    extension: %~nx0
    @echo Extension: %~x0
    @echo Filename as given on command line: %0
    @echo Filename as given on command line minus quotes: %~0
    @REM Build from parts
    @SETLOCAL
    @SET drv=%~d0
    @SET pth=%~p0
    @SET fpath=%~dp0
    @SET fname=%~n0
    @SET ext=%~x0
    @echo Simply Constructed name: %fpath%%fname%%ext%
    @echo Fully  Constructed name: %drv%%pth%%fname%%ext%
    @ENDLOCAL
    pause
    

提交回复
热议问题