我遇到问题的部分脚本如下:
setlocal enabledelayedexpansion
for /r %%a in (*) do (
cd "%%~dpa"
set /A count += 1
set fn=file!count!
%batchdir%\7z.exe a -mx9 -sdel -p"%password%" -mhe=on "!fn!.7z" "%%~nxa"
)
但是 filename 变量无法正确处理带有感叹号的文件名。fn
%%~nxa
!
有办法解决这个问题吗?
谢谢。
编辑:改变fn
这%%~nxa
一点就是问题所在
答案1
是的,启用延迟扩展会抑制未转义的感叹号。有关证据,请参见以下简单脚本及其输出:
@ECHO OFF
pushd d:\bat\Unusual Names\exclamations
echo(
echo dir /B:
dir /B
echo(
echo loop with EnableDelayedExpansion:
SETLOCAL EnableExtensions EnableDelayedExpansion
for /r %%a in (*) do (
echo %%~nxa
)
ENDLOCAL
echo(
echo loop with DisableDelayedExpansion:
SETLOCAL EnableExtensions DisableDelayedExpansion
for /r %%a in (*) do (
echo %%~nxa
)
ENDLOCAL
popd
输出:D:\bat\SU\1552202.bat
dir /B: 01exclam!ation.txt 02exc!lam!ation.txt 04exc!lam!ation!OS!%OS%.txt loop with EnableDelayedExpansion: 01exclamation.txt 02excation.txt 04excationWindows_NT%OS%.txt loop with DisableDelayedExpansion: 01exclam!ation.txt 02exc!lam!ation.txt 04exc!lam!ation!OS!%OS%.txt
请参见这个答案(用感叹号显示了两种处理此类数据的方法)。如果改进,您的脚本可以正常工作,例如:
setlocal EnableExtensions DisableDelayedExpansion
rem ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ ← ← ← important!
set /A count=0
for /r %%a in (*) do (
pushd "%%~dpa"
set "file_nxa=%%~nxa"
call :do7z
popd
)
goto :eof
:do7z
set /A count += 1
set fn=file%count%
%batchdir%\7z.exe a -mx9 -sdel -p"%password%" -mhe=on "%fn%.7z" "%file_nxa%"
goto :eof