[英]Windows batch script "The system cannot find the file specified." with exclamation in filenames?
I am trying to write a batch script that does the following:我正在尝试编写一个执行以下操作的批处理脚本:
When a folder is drag-and-dropped onto the batch script, it processes every file in that folder.将文件夹拖放到批处理脚本上时,它会处理该文件夹中的每个文件。
I am running into a problem with a certain filenames that contain exclamation marks.我遇到了包含感叹号的某些文件名的问题。 eg:例如:
!.txt
or !!!.txt
!.txt
或!!!.txt
For now, I am simply trying to rename the file to demonstrate the issue:现在,我只是尝试重命名文件以演示该问题:
@echo off
SetLocal EnableDelayedExpansion
set folder=%~1
set count=0
for /r "%folder%" %%G in (*) do (
set fullpath=%%G
set fileExtension=%%~xG
call :processFile
)
goto end
:processFile
echo "fullpath = %fullpath%"
echo "fileExtension = %fileExtension%"
rename "%fullpath%" "temporary_filename_500%fileExtension%"
set /a count+=1
echo.
goto :eof
:end
echo "%count% files processed."
pause
It gives me the error "The system cannot find the file specified."它给了我错误“系统找不到指定的文件”。 However, it works if I change the filename to something simple like "test.webm" How can I make the script more robust?但是,如果我将文件名更改为诸如“test.webm”之类的简单名称,它会起作用 如何使脚本更健壮?
I don't see that you are using somewhere delayed expansion.我没有看到您在某处使用延迟扩展。 So, either disable it with setlocal DisableDelayedExpansion
in the start of your batch file or just remove it by removing line setlocal EnableDelayedExpansion
.因此,要么在批处理文件的开头使用setlocal DisableDelayedExpansion
禁用它,要么通过删除行setlocal EnableDelayedExpansion
将其删除。
However, if you want to keep it, do:但是,如果您想保留它,请执行以下操作:
@echo off
SetLocal EnableDelayedExpansion
rem Code above (^^) if exists.
Setlocal DisableDelayedExpansion
set "folder=%~1"
set "count=0"
for /R "%folder%" %%G in (*) do (
set "fullpath=%%~fG"
set "fileExtension=%%~xG"
call :processFile
)
goto end
:processFile
echo "fullpath = %fullpath%"
echo "fileExtension = %fileExtension%"
ren "%fullpath%" "temporary_filename_500%fileExtension%"
set /a "count+=1"
echo/
goto :eof
:end
echo "%count% files processed."
pause
setlocal EnableDelayedExpansion
rem Your code below with active delayed expansion:
Note that:注意:
set
command like set "var=value"
and in set /a
like set /a "var+=1"
, etc.;您应该始终引用set
命令中的变量名称和值,例如set "var=value"
和set /a
例如set /a "var+=1"
等; see set /?
见set /?
for more information.想要查询更多的信息。for
loop, use the f
modifier, like %%~fG
.要在for
循环中确定找到文件/文件夹的完整路径,请使用f
修饰符,例如%%~fG
。echo.
Mofi 在这里提到:不要使用echo.
; ; use echo/
for better practice.使用echo/
以获得更好的练习。See also the Phase 5 (Delayed Expansion) of this answer about how batch files are interpreted.另请参阅此答案的第 5 阶段(延迟扩展),了解如何解释批处理文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.