basic

常用變數

批次檔所在目錄

㊙️ 不在批次檔內,無效

echo %~dp0
cd /d "%~dp0"

目前工作目錄:%CD%

echo %CD%

目前磁碟機

echo %CD:~0,3%

命令列參數

假設在命令列鍵入了下列指令

test.cmd c:\windows\notepad.exe c:\windows\write.exe 此時批次檔可拿取的對應變數如下:

%0 (命令) test.cmd
%1 (參數1) c:\windows\notepad.exe
%2 (參數2) c:\windows\write.exe

%1 的擴充

上述%1的參數對應,可以加以擴充,例如d,p,n x:

%1	%~d1 (取得磁碟機代號)	%~p1 (取得路徑)	%~n1 (取得檔名)	%~x1 (取得副檔名)
c:\windows\notepad.exe	c:	\Windows\	notepad	.exe

列表

%~1         - expands %1 removing any surrounding quotes (")
%~f1        - expands %1 to a fully qualified path name
%~d1        - expands %1 to a drive letter only
%~p1        - expands %1 to a path only
%~n1        - expands %1 to a file name only
%~x1        - expands %1 to a file extension only
%~s1        - expanded path contains short names only
%~a1        - expands %1 to file attributes
%~t1        - expands %1 to date/time of file
%~z1        - expands %1 to size of file

The modifiers can be combined to get compound results:

%~dp1       - expands %1 to a drive letter and path only
%~nx1       - expands %1 to a file name and extension only
~% FILE="example.tar.gz"

~% echo "${FILE%%.*}"
example

~% echo "${FILE%.*}"
example.tar

~% echo "${FILE#*.}"
tar.gz

~% echo "${FILE##*.}"
gz

demo

@echo off
setlocal disableDelayedExpansion
pushd %1
set "tab=    "
set "indent="
call :run >report.txt
exit /b

:run
for %%F in (.) do echo %%~fF

:listFolder
setlocal
set "indent=%indent%%tab%"
for %%F in (*) do echo %indent%%%~tF   %%F
for /d %%F in (*) do (
  echo %indent%.\%%F
  pushd "%%F"
  call :listFolder
  popd
)
exit /b
@echo off
setlocal disableDelayedExpansion
pushd %1
call :run 
exit /b

:run
for %%F in (.) do echo %%~fF

:listFolder
setlocal
set "indent=%indent%%tab%"
for %%F in (*) do echo  %%F
for /d %%F in (*) do (
  echo %%F
  pushd "%%F"
  call :listFolder
  popd
)
exit /b

demo3:How do I isolate filename and extension from %1?

Use the following batch file (split.bat):

@echo off 
setlocal
REM usage split.bat <filename>
set _filename=%~n1
set _extension=%~x1
echo input file name is ^<%_filename%^> and extension is ^<%_extension%^>
endlocal  

Notes:

Example usage:

split testfile.txt input file name is and extension is <.txt>