如何使用环境变量复制和重命名文件?



我几乎是第一次使用命令提示符,并且需要创建一个批处理文件,提示用户输入带有扩展名的文件名。蝙蝠应该能够复制和重命名所述文件。讲师指示我们使用环境变量来完成此任务,但我不断收到目录或语法错误。

我尝试使用用户在上一个提示下设置的变量,但不幸的是,这位特定的讲师没有给我们提供有关如何实现此特定目标的实际示例,所以我很生气。我尝试使用文件的通用名称将变量附加到目标目录。文件和副本应位于 dame 目录中。

set /P file_var=Please enter a file name and extension: 
copy %file_var% Templatecopy.doc

应在目标目录中使用新的默认名称"模板复制.doc"复制该文件。

大量处理语法和目录错误。

我建议使用以下注释代码使此批处理文件具有故障安全功能,如如何阻止 Windows 命令解释器在用户输入不正确时退出批处理文件执行?

@echo off
:FileNamePrompt
rem Undefine environment variable FileToCopy.
set "FileToCopy="
rem Prompt user for the file name.
set /P "FileToCopy=Please enter a file name and extension: "
rem Has the user not entered anything, prompt the user once more.
if not defined FileToCopy goto FileNamePrompt
rem Remove all double quotes from user input string.
set "FileToCopy=%FileToCopy:"=%"
rem Has the user input just one or more ", prompt the user once more.
if not defined FileToCopy goto FileNamePrompt
rem Check if the user input string really references an existing file.
if not exist "%FileToCopy%" (
echo File "%FileToCopy%" does not exist.
goto FileNamePrompt
)
rem Check if the user input string really references
rem an existing file and not an existing directory.
if exist "%FileToCopy%" (
echo "%FileToCopy%" references a directory.
goto FileNamePrompt
)
copy /B /Y "%FileToCopy%" "%~dp0Templatecopy.doc" >nul

要了解使用的命令及其工作原理,请打开命令提示符窗口,在那里执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。

  • call /?......解释了%~dp0扩展到驱动器和参数 0 的路径,这是始终以反斜杠结尾的批处理文件路径。
  • copy /?
  • echo /?
  • goto /?
  • if /?
  • rem /?
  • set /?

最新更新