有人可以协助执行批处理移动脚本吗?
我希望脚本提示输入文件源路径,文件目标路径和文件名。
然后从以上3个文件中移动文件。我有一个脚本,可以搜索文件是否存在并在记事本中显示结果。希望为此添加到上面。
@echo off
:start
set /p filesource="Enter file source path: "
set /p filedestination="Enter file destination path: "
set /p filename="Enter file name to look for: "
if "%filesource%"=="" goto :error
if "%filedestination%"=="" goto :error
if "%filename%"=="" goto :error
echo Moving %filename% From "%filesource%\%filename%" to %filedestination%.
>> %f%
move "%filesource%\%filename%" %filedestination
echo. >> %f%
notepad %f%
goto :end
:error
echo You did not enter correct information.
pause
goto :start
:end
答案 0 :(得分:0)
主要错误在于命令行:
move "%filesource%\%filename%" %filedestination
引用环境变量%
时缺少第二个filedestination
。
如果包含空格或以下字符之一&()[]{}^=;!'+,`~<|>
,则目标路径也应用双引号引起来。
并且应确保目标路径确实以反斜杠结尾以将文件移至该目录,因为否则可能会将文件移至具有不同文件名的目录。
因此此命令行应为:
move "%filesource%\%filename%" "%filedestination%\"
但是,老实说,批处理文件需要更多代码才能确保安全。例如:
@echo off
goto Main
:UserPrompt
set "UserInput="
set /P "UserInput=Enter file %~2: "
rem Has the user entered no string?
if not defined UserInput goto ErrorInput
rem Remove all double quotes.
set "UserInput=%UserInput:"=%"
rem Has the user entered a string consisting only of double quotes?
if not defined UserInput goto ErrorInput
rem Check if file or directory exist at all.
if %1 == FileName (
rem The file name should not contain a directory separator.
if not "%UserInput:\=%" == "%UserInput%" goto ErrorInput
if not "%UserInput:/=%" == "%UserInput%" goto ErrorInput
if not exist "%FileSource%%UserInput%" (
echo/
echo There is no file "%FileSource%%UserInput%"
echo/
pause
echo/
goto UserPrompt
)
rem Prevent moving the batch file.
for %%I in ("%FileSource%%UserInput%") do if "%%~fI" == "%~f0" (
echo/
echo This batch file cannot be moved.
echo/
pause
echo/
goto UserPrompt
)
goto ReturnValue
)
rem Get full path in case of user entered a relative path.
for %%I in ("%UserInput%") do set "UserInput=%%~fI"
if not "%UserInput:~-1%" == "\" set "UserInput=%UserInput%\"
if not exist "%UserInput%" (
echo/
echo There is no directory "%UserInput%"
echo/
pause
echo/
goto UserPrompt
)
:ReturnValue
set "%1=%UserInput%"
goto :EOF
:ErrorInput
echo/
echo You did not enter correct information.
echo/
pause
echo/
goto UserPrompt
:Main
setlocal EnableExtensions DisableDelayedExpansion
call :UserPrompt FileSource "source path"
call :UserPrompt FileTarget "destination path"
call :UserPrompt FileName "name to look for"
set "LogFile=%TEMP%\%~n0.tmp"
echo Moving "%FileName%" from "%FileSource%" to "%FileTarget%".>"%LogFile%"
move /Y "%FileSource%%FileName%" "%FileTarget%" 2>>"%LogFile%"
echo/>>"%LogFile%"
Notepad.exe "%LogFile%"
del "%LogFile%" 2>nul
endlocal
要了解所使用的命令及其工作方式,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。
call /?
del /?
echo /?
endlocal /?
for /?
goto /?
if /?
move /?
pause /?
rem /?
set /?
setlocal /?
另请参阅: