CMD:如何使用通配符复制可执行文件作为路径名?

时间:2016-11-12 21:09:06

标签: batch-file cmd copy

使用Windows CMD / BAT,如果我没有源文件的ABSOLUTE位置,我怎么能将文件(在这种情况下是可执行文件/ .exe文件)复制到新位置?我对CMD和BAT文件很新。

指定的文件本身取决于用户的输入;因此,代码本身没有指定所述文件的路径。

实施例。将MSpaint.exe(位于C:\ Windows \ System32中,虽然对于问题的上下文,我们不知道)复制到名为PAINT的桌面文件夹。

我尝试过使用

copy "*\mspaint.exe" "C:\Users\User\Desktop\PAINT"

但错误陈述说

The filename, directory name, or volume label syntax is incorrect.
    0 files(s) copied.

我尝试使用没有通配符路径的命令,没有进一步的效果。

copy "mspaint.exe" "C:\Users\User\Desktop\PAINT"

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

一个很少使用的特殊变量扩展是穷人的where.exe ;-) 因此,如果查找文件位于搜索路径中的某个位置:

编辑已更改为将exe放入var中,该var在找到时会扩展为完整路径。

Set "EXE=mspaint.exe" & set MyPath=.;%Path%
for %%A in (%EXE%) do Set EXE=%%~$MyPath:A
If defined EXE copy "%EXE%" "C:\Users\User\Desktop\PAINT"
Cite from for /?
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

答案 1 :(得分:0)

以下是一个简单的批处理代码示例:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "FileToFind="
set /P "FileToFind=Please enter file name: "
for /F %%I in ('dir "C:\!FileToFind!" /A-D /B /S 2^>nul') do (
    set "FilePath=%%~dpI"
    goto FileFound
)
echo Could not find !FileToFind! on drive C:
goto EndBatch

:FileFound
echo Found !FileToFind! in %FilePath%

:EndBatch
echo.
endlocal
pause

此批处理代码还可以分别在驱动器C上的隐藏或系统目录中找到隐藏文件或系统文件。

忽略隐藏和系统目录/文件的替代解决方案是:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "FileToFind="
set /P "FileToFind=Please enter file name: "
for /R "C:\" %%I in ("!FileToFind!*") do (
    set "FilePath=%%~dpI"
    goto FileFound
)
echo Could not find !FileToFind! on drive C:
goto EndBatch

:FileFound
echo Found !FileToFind! in %FilePath%

:EndBatch
echo.
endlocal
pause

此解决方案的另一个缺点是,在输入test.txt时,它还会找到test.txt.bak

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

  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • pause /?
  • set /?
  • setlocal /?